How to get the difference between two arrays in Javascript likeArray([1, 2, 3, 7], [3, 2, 1, 4, 5]);//[1,2,3]
Asked
Active
Viewed 46 times
-5
-
1What do you mean by the difference? The difference of the sums of the numbers? Please provide more information. – adprocas Mar 14 '18 at 15:02
-
1Read [ask] and create a [mcve] – Alon Eitan Mar 14 '18 at 15:02
2 Answers
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))

Luis felipe De jesus Munoz
- 7,454
- 2
- 33
- 53
-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
-
-
@LuisfelipeDejesusMunoz Yes I goofed with hitting send too early, deleted it right away and fixed it. Sorry for that mistake. – Vulpex Mar 14 '18 at 15:08