I have two arrays
a[] = [1,2,3,4]
b[] = [1,4]
Need to remove elements of array b from array a.
Expected output:
a[] = [1,4]
I would use the filter method:
a = a.filter(function (item) {
return b.indexOf(item) === -1;
});
Take a look at the jQuery docs for $.grep and $.inArray.
Here's what the code would look like:
var first = [1,2,3,4],
second = [3,4];
var firstExcludeSecond = $.grep(first, function(ele, ix){ return $.inArray(ele, second) === -1; });
console.log(firstExcludeSecond);
Basically amounts to iterating through the first array ($.grep) and determining if a given value is in the second array ($.inArray). If the value returned from $.inArray is -1, the value from the first array does not exist in the second so we grab it.
I'm looping over the second array, and checking if the value is in the first array using indexOf If it is I use splice to remove it.
var a = [1,2,3,4,5];
var b = [3,4,5];
b.forEach(function(val){
var foundIndex = a.indexOf(val);
if(foundIndex != -1){
a.splice(foundIndex, 1);
}
});
Or
var a = [1,2,3,4,5];
var b = [3,4,5];
a = a.filter(x => b.indexOf(x) == -1);
For IE 8,
for(var i = 0; i < b.length; i++){
var val = b[i];
var foundIndex = a.indexOf(val);
if(foundIndex != -1){
a.splice(foundIndex, 1);
}
}