Find the Even numbers in an Array using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Find the Even Numbers in an Array #

To find the even numbers in an array:

  1. Use the Array.filter() method to iterate over the array.
  2. Check if each number doesn't have a remainder when divided by 2.
  3. The filter method will return a new array containing only the even numbers
index.js
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.

If the function returns a truthy value, the element is included in the new array.

On each iteration, we use the modulo (%) operator to check if the number doesn't have a remainder when divided by 2.

index.js
console.log(10 % 2); // 👉️ 0 console.log(11 % 2); // 👉️ 1

If there is no remainder when the number is divided by 2, it's an even number.

Only even numbers satisfy the condition and get added to the new array.

An alternative approach is to use the Array.forEach method.

To find the even numbers in an array:

  1. Declare a variable and initialize it to an empty array.
  2. Use the Array.forEach() method to iterate over the array.
  3. Check if each number doesn't have a remainder when divided by 2.
  4. If there is no remainder, push the number into the even numbers array.
index.js
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.

The forEach method returns undefined, so we have to create a new array to store the results.

Which approach you pick is a matter of personal preference. I'd go with the filter() method because it helps us avoid declaring an intermediary variable.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.