Find difference between two arrays in JavaScript
This post will discuss how to find the difference between two arrays in JavaScript. The solution should return an array containing all the elements of the first array which are not present in the second array.
For example, the difference between arrays [1,2,3,4] and [3,4,5] is [1,2].
1. Using Array.prototype.filter() function
You can use the filter() method to find the elements of the first array which are not in the second array. This filtering can be done using the:
a) indexOf() method
|
1 2 3 4 5 6 7 8 9 |
var first = [ 1, 2, 3, 4, 5 ]; var second = [ 4, 5, 6 ]; var difference = first.filter(x => second.indexOf(x) === -1); console.log(difference); /* Output: [ 1, 2, 3] */ |
b). ES7 includes() method
|
1 2 3 4 5 6 7 8 9 |
var first = [ 1, 2, 3, 4, 5 ]; var second = [ 4, 5, 6 ]; var difference = first.filter(x => !second.includes(x)); console.log(difference); /* Output: [ 1, 2, 3] */ |
c). ES6 Set Object
|
1 2 3 4 5 6 7 8 9 10 11 |
var first = [ 1, 2, 3, 4, 5 ]; var second = [ 4, 5, 6 ]; var b = new Set(second); var difference = [...first].filter(x => !b.has(x)); console.log(difference); /* Output: [ 1, 2, 3] */ |
2. Using jQuery
With jQuery, you can use the .not() method to get the difference. To get the items of the first array which doesn’t exist in the second array, use the following code:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
const { JSDOM } = require("jsdom"); const { window } = new JSDOM(); var $ = require("jquery")(window); var first = [ 1, 2, 3, 4, 5 ]; var second = [ 4, 5, 6 ]; var difference = $(first).not(second).get(); console.log(difference); /* Output: [ 1, 2, 3] */ |
Alternatively, you can use the grep() method, which works similarly to the JavaScript filter() method. The following example demonstrates its usage by removing items from the first array, which fails the specified condition.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
const { JSDOM } = require("jsdom"); const { window } = new JSDOM(); var $ = require("jquery")(window); var first = [ 1, 2, 3, 4, 5 ]; var second = [ 4, 5, 6 ]; var difference = $.grep(first, (item) => $.inArray(item, second) === -1); console.log(difference); /* Output: [ 1, 2, 3] */ |
3. Using Underscore/Lodash Library
The Underscore and Lodash Library provides their implementation of the difference method _.difference, which returns values from an array that are not included in the other array.
|
1 2 3 4 5 6 7 8 9 10 11 |
var _ = require('underscore'); var first = [ 1, 2, 3, 4, 5 ]; var second = [ 4, 5, 6 ]; var difference = _.difference(first, second); console.log(difference); /* Output: [ 1, 2, 3] */ |
That’s all about finding the difference between two arrays in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)