How to use filter Method In Javascript
- Declare an array called “numbers” containing a set of integers.
- Use the filter() method on the “numbers” array, passing in a callback function as the argument.
- The callback function should take in the current element as a parameter and use the modulus operator (element%2==0) to check if it is even.
- Return true for even numbers and false for odd numbers in the callback function.
- Assign the returned result of the filter method to a variable, let’s say ‘evenNumbers’.
- After the filter method, use console.log() to display the message “Even numbers in an array are: [evenNumbers]” where [evenNumbers] is the array of even numbers returned from the filter method.
The filter method returns a new array with all elements that pass the test implemented by the callback function.
Example: In this example, we are Using filter Method
Javascript
// Initializing numbers array let numbers = [86, 41, 55, 85, 90, 24]; let evenNumbers = numbers.filter( function (element) { return element % 2 === 0; }); // Printing output console.log(`Even numbers in an array are: ${evenNumbers}`); |
Output
Even numbers in an array are: 86,90,24
JavaScript program to print even numbers in an array
Given an array of numbers and the task is to write a JavaScript program to print all even numbers in that array.
We will use the following methods to find even numbers in an array:
Table of Content
- Using for Loop
- Using while Loop
- Using forEach Loop
- Using filter Method
- Using for…of Loop
Example:
Input: numbers_array1= [4, 76, 89, 61, 72, 64]
Output: [4,76,72,64]
Input: numbers_array2= [15, 60, 90, 14, 7, 45]
Output: [60,90,14]