Javascript -- Compare two arrays, return differences, BUT

Just iterate over the array of elements you want to remove.

var array1 = ['A', 'B', 'C', 'D', 'D', 'E'];
var array2 = ['D', 'E'];
var index;

for (var i=0; i<array2.length; i++) {
    index = array1.indexOf(array2[i]);
    if (index > -1) {
        array1.splice(index, 1);
    }
}

It's O(array1.length * array2.length) but for reasonably small arrays and on modern hardware this shouldn't remotely cause an issue.

http://jsfiddle.net/mattball/puz7q/

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/splice


You can use Filter also. Please review below example.

var item = [2,3,4,5];
var oldItems = [2,3,6,8,9];
oldItems = oldItems.filter(n=>!item.includes(n))

so this will return [6,8,9]

and if you want to get only matched items then you have to write below code.

oldItems = oldItems.filter(n=>item.includes(n))

This will return [2,3] only.

Tags:

Javascript