Filter even numbers in array in JavaScript
In this tutorial, you are given an array. Write a JavaScript program to filter even numbers in the array.
Solution
To filter even numbers in the given array using JavaScript, we can use Array.filter() method. Call filter()
method on the given array, and pass a function that returns true
for even number, or false
otherwise. filter()
method returns a new array with the even numbers from the contents of original array.
Program
1. Filter even numbers in the nums
array.
function isEven(item) {
if (item % 2 == 0) {
return true;
} else {
return false;
}
}
nums = [4 , 5, 2, 0, 1, 7, 19, 82];
evenNums = nums.filter(isEven);
console.log(evenNums);