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?
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?
Just use Array#filter() and Array#indexOf() with bitwise not ~ operator for checking.
~is a bitwise not operator. It is perfect for use withindexOf(), becauseindexOfreturns if found the index0 ... nand 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>");
in jquery with inArray method:
for(array1)
var idx = $.inArray(array1[i], array2);
if (idx != -1) {//-1 not exists
array2.splice(idx, 1);
}
}
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)