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.
Approach: If the given array is [5, 6, 7, 8, 9, 2, 6, 3, -4, 0, -9, -6] and the task is to filter out the negative values and want to print that values.
Let us create a function that returns true if the value is positive otherwise it returns the false.
In order to filter out the array, we will loop through the array and call this function “myFilter“. The value is skipped if it returns true, if the function returns false, then we will store that value in the filteredArr by using “filteredArr.push()” the filtered array. We use forEach loop through the array elements.
After filtering : [ -4, -9, -6 ]
Example 2: To filter the positive values, we can either change our myFilter function or code section of forEach loop. If we change the condition in the myFilter function for less than zero, the function will return false for positive value instead. We will store those positive values in filteredArr.
After filtering : [ 5, 6, 7, 8, 9, 2, 6, 3, 0 ]
We have successfully filtered the array for which the function does not return true.