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]
-
2Do you mean b[] = [2,3] ? To have what you expected as a[] = [1,4].Hashim Otto– Hashim Otto2019年07月17日 04:21:57 +00:00Commented Jul 17, 2019 at 4:21
5 Answers 5
I would use the filter method:
a = a.filter(function (item) {
return b.indexOf(item) === -1;
});
const array_diff = (a, b) => a.filter(v => !b.includes(v))
If you want to support IE
const array_diff = (a, b) => a.filter(v => b.indexOf(v) === -1);
Comments
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.
Comments
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);
}
}
4 Comments
function myFunction(a, b) {
return a.filter(item => b.indexOf(item) < 0)
}
console.log(myFunction([1, 2, 3], [1, 2]))