w3resource

JavaScript: Filter out all values from an array for which the comparator function does not return true

JavaScript fundamental (ES6 Syntax): Exercise-74 with Solution

Filter Array by Comparator

Write a JavaScript program to filter out all values from an array for which the comparator function does not return true.

  • Use Array.prototype.filter() and Array.prototype.findIndex() to find the appropriate values.
  • Omit the last argument, comp, to use a default strict equality comparator.

Sample Solution:

JavaScript Code:

//#Source https://bit.ly/2neWfJ2
// Define a function 'differenceWith' to find the difference between two arrays based on a provided comparison function.
const differenceWith = (arr, val, comp) =>
  // Filter array 'arr' to keep only those elements for which no element in array 'val' satisfies the comparison function 'comp'.
  arr.filter(a => val.findIndex(b => comp(a, b)) === -1);

// Example usage:
console.log(differenceWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0], (a, b) => Math.round(a) === Math.round(b)));

Output:

[1,1.2]

Flowchart:

flowchart: Filter out all values from an array for which the comparator function does not return trues

Live Demo:

See the Pen javascript-basic-exercise-74-1 by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript program that filters an array by keeping only the values that pass a custom comparator function.
  • Write a JavaScript function that iterates over an array and excludes elements for which the comparator returns false.
  • Write a JavaScript program that applies a comparator to each array element and returns a new array with elements meeting the criteria.

Go to:


PREV : Difference Between Two Arrays with Mapping.
NEXT : Elo Rating System Computation.

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.