[SOLVED] How to create function which return only even numbers in array?

Issue

Write a function that takes one argument, which is an array of numbers, and returns an array that contains only the numbers from the input array that are even.

Solution

Step by step walkthrough:

  1. We create 3 arrays, 1 containing only even numbers, one only containing uneven numbers, one containing both
  2. We create the function returnEvenNumbersFromArray(array)
  3. We create an empty array finishedArray to store the even numbers to return if the function has finished
  4. We iterate over the array that was passed to the function, checking if it is even

Running num % 2 returns a 0 (false) if the number isnt even, and a 1 (true) if it is even.

  1. Every even number is pushed into our finishedArray
  2. We return the finishedArray
evenNumbers = [2,4,6,8,10,12,16]
unevenNumbers = [1,3,5,7,9,11,15]
mixedNumbers = [0, 1, 6, 7, 3, 14]
function returnEvenNumbersFromArray(array) {
	finishedArray = []
	array.forEach(function(num) {
  	if(!(num % 2)) {
    	finishedArray.push(num)
    }
  })
  return finishedArray;
}
console.log(returnEvenNumbersFromArray(evenNumbers)) 
console.log(returnEvenNumbersFromArray(unevenNumbers)) 
console.log(returnEvenNumbersFromArray(mixedNumbers)) 

Answered By – Altay Akkus

Answer Checked By – Willingham (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *