Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How to get the difference between two arrays in JavaScript?

Is there an approach to return the distinction between two arrays in JavaScript?

For example:
var a1 = ['a', 'b'];
var a2 = ['a', 'b', 'c', 'd'];

// need ["c", "d"]
by

2 Answers

akshay1995

Array.prototype.diff = function(a) {
return this.filter(function(i) {return a.indexOf(i) < 0;});
};

//////////////
// Examples //
//////////////

const dif1 = [1,2,3,4,5,6].diff( [3,4,5] );
console.log(dif1); // => [1, 2, 6]


const dif2 = ["test1", "test2","test3","test4","test5","test6"].diff(["test1","test2","test3","test4"]);
console.log(dif2); // => ["test5", "test6"]
kshitijrana14
This is by far the easiest way to get exactly the result you are looking for, using jQuery:
var diff = $(old_array).not(new_array).get();

diff now contains what was in old_array that is not in new_array

Login / Signup to Answer the Question.