-5

How to get the difference between two arrays in Javascript likeArray([1, 2, 3, 7], [3, 2, 1, 4, 5]);//[1,2,3]

2 Answers2

1

There is a little function that compares 2 arrays and get the difference. The first parameter is you array and the second the one you want to compare to

var array1 = [1, 2, 3, 7]
var array2 = [3, 2, 1, 4, 5]

Diff = function(a, d){
  return a.filter(_=>d.indexOf(_)<0)
}

console.log(Diff(array1, array2))

console.log(Diff(array2, array1))
-1

Pretty easy if you're supporting "newer" browsers.

    Array.prototype.diff = function (x) {
    return this.filter(function (y) {
        return a.indexOf(i) === -1;
    });
};

then you can call it like

[1, 2, 3, 4, 5, 6].diff([2, 4, 6]);

Vulpex
  • 1,041
  • 8
  • 19