How to use filter() Method In Javascript
In this method, we will use the filter() method and comparator function. The comparator function gives the true for odd numbers because value%2 gives the zero which is false in the boolean.
Example:
Javascript
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let filteredArr = []; const myFilter = (value) => { return Boolean(value % 2); }; arr.filter((element) => { if (myFilter(element) === false ) { filteredArr.push(element); } }); console.log(filteredArr); |
Output
[ 2, 4, 6, 8, 10 ]
How to filter values from an array for which the comparator function does not return true in JavaScript ?
The task is to filter the array based on the returned value when passed to the given function. The purpose is to loop through the array and execute one function that will return true or false. Then filter out all the values for which the function (comparator function) does not return true.
These are the following methods for filtering the values from an array:
- Using forEach() method
- Using filter() Method
- Using for() loop
Approach:
- Start by defining an array named ‘array’ and assign the values to it.
- Define a comparator function name
compare
that will be used to filter the elements. - Apply different methods to get the filtered values.
Contact Us