To find the even numbers in an array, you should follow the following steps:
true
, and that array element becomes a member of the new array.let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let evenNumbers = numbers.filter(number => { if(number % 2 == 0){ return true; } }); console.log(evenNumbers); //[2, 4, 6, 8, 10]
The callback function of the filter() method is called for each element of the array. Inside the callback function, you mention the condition using the modulo operator (%) to check if a number is divisible by 2 or not. If the value returned by the modulo operator is 0, then the number is divisible by 2; otherwise, it is not divisible by 2.
When a number is divisible by 2, then return true so that number becomes a part of the new array, and in this way, you can find even numbers in an array.
An alternative way is to use the forEach() method.
To find the even numbers in an array using the forEach() method, you must follow the following steps:
forEach()
method on the array in which you want to find even numbers.let evenNumbers = []; let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; numbers.forEach(number => { if(number % 2 == 0){ evenNumbers.push(number); } }); console.log(evenNumbers); //[2, 4, 6, 8, 10]