How to create a function which returns only even numbers in JavaScript array?


Here, we need to 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.

So, let's name the function as returnEvenArray, the code for the function will be −

Example

const arr = [3,5,6,7,8,4,2,1,66,77];
const returnEvenArray = (arr) => {
   return arr.filter(el => {
      return el % 2 === 0;
   })
};
console.log(returnEvenArray(arr));

We just returned a filtered array that only contains elements that are multiples of 2.

Output

Output in the console will be −

[ 6, 8, 4, 2, 66 ]

Above, we returned only even numbers as output.

Updated on: 18-Aug-2020

754 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements