JavaScript: Return the difference between two arrays
JavaScript fundamental (ES6 Syntax): Exercise-73 with Solution
Write a JavaScript program to return the difference between two arrays, after applying the provided function to each array element of both.
- Create a Set by applying fn to each element in b.
- Use Array.prototype.map() to apply fn to each element in a.
- Use Array.prototype.filter() in combination with fn on a to only keep values not contained in b, using Set.prototype.has().
Sample Solution:
JavaScript Code:
//#Source https://bit.ly/2neWfJ2
const differenceBy = (a, b, fn) => {
const s = new Set(b.map(v => fn(v)));
return a.filter(x => !s.has(fn(x)));
};
console.log(differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor));
console.log(differenceBy([{ x: 2 }, { x: 1 }], [{ x: 1 }], v => v.x));
Sample Output:
[1.2] [{"x":2}]
Flowchart:

Live Demo:
See the Pen javascript-fundamental-exercise-73 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus
Previous: Write a JavaScript program to detect if the website is being opened in a mobile device or a desktop/laptop.
Next: Write a JavaScript program to filter out all values from an array for which the comparator function does not return true.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join