Problem Statement
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);