Reputation: 3082
So I have one array:
var array1 = ['one', 'two', 'three', 'four', 'five']
And another:
var array2 = ['two, 'four']
How can I remove all the strings from array2
out of array1
?
Upvotes: 4
Views: 66
Reputation: 1221
var array1 = ['one', 'two', 'three', 'four', 'five']
var array2 = ['two', 'four']
array1 = array1.filter(function(item){
return array2.indexOf(item) === -1
})
// ['one', 'three', 'four', 'five']
document.write(array1)
Upvotes: 0
Reputation: 2615
in jquery with inArray method:
for(array1)
var idx = $.inArray(array1[i], array2);
if (idx != -1) {//-1 not exists
array2.splice(idx, 1);
}
}
Upvotes: 0
Reputation: 386654
Just use Array#filter()
and Array#indexOf()
with bitwise not ~
operator for checking.
~
is a bitwise not operator. It is perfect for use withindexOf()
, becauseindexOf
returns if found the index0 ... n
and if not-1
:value ~value boolean -1 => 0 => false 0 => -1 => true 1 => -2 => true 2 => -3 => true and so on
var array1 = ['one', 'two', 'three', 'four', 'five'],
array2 = ['two', 'four'];
array1 = array1.filter(function (a) {
return !~array2.indexOf(a);
});
document.write("<pre>" + JSON.stringify(array1, 0, 4) + "</pre>");
Upvotes: 4
Reputation: 14876
Try this.
array2.forEach(item => array1.splice(array1.indexOf(item),1));
Upvotes: 2