How to use for() loop In Javascript
In this method, we will use for() loop for iterating over the array and then use the comparator function for comparing the values.
Example:
Javascript
const arr = [5, 6, 7, 8, 9, 2, 6, 3, -4, 0, -9, -6]; // Filtered array for which function // returned false let filteredArr = []; // Comparator function const myFilter = (element) => { if (element >= 0) { return true ; } else { return false ; } } for (i = 0; i < arr.length; i++) { if (myFilter(arr[i])=== false ) { filteredArr.push(arr[i]); } } console.log(filteredArr); |
Output
[ -4, -9, -6 ]
We have successfully filtered the array for which the function does not return true.
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