Problem
Is there a method in JavaScript to get the difference between two arrays?
For example:
var a1 = ['a', 'b'];
var a2 = ['a', 'b', 'c', 'd'];
// need ["c", "d"]
Asked by John Adawan
Solution #1
There’s a better way to do it with ES7:
Intersection
let intersection = arr1.filter(x => arr2.includes(x));
It will return [2,3] for [1,2,3]. For [1,2,3] [2,3,5], on the other hand, the result will be the same.
Difference
let difference = arr1.filter(x => !arr2.includes(x));
It will yield [1] for [1,2,3] [2,3]. For [1,2,3] [2,3,5], on the other hand, the result will be the same.
You can make a symmetric difference by:
let difference = arr1
.filter(x => !arr2.includes(x))
.concat(arr2.filter(x => !arr1.includes(x)));
You’ll obtain an array containing all of arr1’s elements that aren’t in arr2, and vice versa.
You can add this to Array.prototype, as @Joshaven Potter mentioned in his answer, so it can be used like this:
Array.prototype.diff = function(arr2) { return this.filter(x => !arr2.includes(x)); }
[1, 2, 3].diff([2, 3])
Answered by Luis Sieira
Solution #2
Note .indexOf() and .filter() are not available before IE9.
Answered by Joshaven Potter
Solution #3
This response was written in 2009, so it’s a little out of current, but it’s still useful for understanding the problem. Today, the best solution I’d utilize is
let difference = arr1.filter(x => !arr2.includes(x));
(Another author’s credit is given here)
I’m assuming you’re comparing two arrays. If this isn’t the case, replace the for loop with a for.. in loop.
Answered by Thinker
Solution #4
Using jQuery, this is by far the simplest approach to obtain exactly the output you want:
var diff = $(old_array).not(new_array).get();
What was in old array but isn’t in new array is now in diff.
Answered by superphonic
Solution #5
Underscore’s difference approach (or its drop-in successor, Lo-Dash) can also do this:
(R)eturns the values from array that are not present in the other arrays
_.difference([1, 2, 3, 4, 5], [5, 2, 10]);
=> [1, 3, 4]
You might use it in a more object-oriented approach, as you could with any Underscore function:
_([1, 2, 3, 4, 5]).difference([5, 2, 10]);
Answered by mahemoff
Post is based on https://stackoverflow.com/questions/1187518/how-to-get-the-difference-between-two-arrays-in-javascript