JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to find even numbers in an array using JavaScript?

To find the even numbers in an array, you should follow the following steps:

  1. First, call the filter() method on the array in which you want to find even numbers.
  2. Inside the callback function of the filter() method, specify the condition that will check whether an array element is divisible by 2 or not.
  3. If a number is divisible by 2, then return 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:

  1. Create an empty array in which you will store the even numbers of the array.
  2. Call the forEach() method on the array in which you want to find even numbers.
  3. Specify the condition inside the callback function of the forEach() method. The condition will check if a number is divisible by 2 or not.
  4. If the number is divisible by 2, then push that array element to the new array created in step 1.
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]

Recommended Posts