Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two arrays and find items that are missing in second array [duplicate]

I have 2 arrays that they are identical at first but the user may remove (not able to add but just remove) items from the second array. I want to find items that are in the first array but not in the second one.

I can think of several ways to do this, but as these arrays can be very large, I'm curious to find out if anyone can offer a more efficient way:

$.grep( firstArray, function( n, i ){
  return $.inArray(n, secondArray) == -1;
});
like image 473
Ashkan Mobayen Khiabani Avatar asked Dec 02 '22 10:12

Ashkan Mobayen Khiabani


2 Answers

You could try to make use of filter and indexOf array methods as below:

var firstArray = [1,2,3,4,5,6];
var secondArray = [3,4,6];

var result = firstArray.filter(item => secondArray.indexOf(item) == -1);

console.log(result);
like image 173
Christos Avatar answered Dec 04 '22 05:12

Christos


Assuming the arrays have the same order, then you could filter with an index as closure.

var array1 = [1, 2, 3, 4, 5, 6, 7, 1, 2, 3],
    array2 = [2, 4, 6, 7, 2],
    missing = array1.filter((i => a => a !== array2[i] || !++i)(0));
    
console.log(missing);
like image 45
Nina Scholz Avatar answered Dec 04 '22 06:12

Nina Scholz