'Remove elements of an array from another array using javascript
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]
Solution 1:[1]
I would use the filter method:
a = a.filter(function (item) {
return b.indexOf(item) === -1;
});
Solution 2:[2]
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);
Solution 3:[3]
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.
Solution 4:[4]
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);
}
}
Solution 5:[5]
function myFunction(a, b) {
return a.filter(item => b.indexOf(item) < 0)
}
console.log(myFunction([1, 2, 3], [1, 2]))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | Tyler Burki |
| Solution 4 | |
| Solution 5 | Muneer Khan |
