Borislav Hadzhiev
Wed Oct 27 2021·2 min read
Photo by Max Vertsanov
To find the even numbers in an array:
filter()
method, passing it a function.filter
method returns a new array containing the elements that satisfy
the condition.const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]; const even = arr.filter(number => { return number % 2 === 0; }); console.log(even); // 👉️ [2, 4, 6, 8]
The function we passed to the Array.filter method gets called with each element in the array.
On each iteration, we use the
modulo (%)
operator to check if the number doesn't have a remainder when divided by 2
.
If there is no remainder when the number is divided by 2
, it's an even number.
Only even
numbers satisfy our condition and will be included in the array
that the filter
method returns.
An alternative approach is to use the Array.forEach method.
To find the even numbers in an array:
forEach
method to iterate over the array and verify if each number
has a remainder when divided by 2
.const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]; const even = []; arr.forEach(number => { if (number % 2 === 0) { even.push(number); } }); console.log(even); // 👉️ [2, 4, 6, 8]
The function we passed to the forEach
method gets called with each element in
the array.
However, the forEach
method doesn't return an array like filter
does.
forEach
method returns undefined
, so we have to create a new array to store the results.Once the method has iterated over the entire array the even
array will contain
all even numbers from the original array.