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]
For removing one array from another array in java we will use the removeAll() method. This will remove all the elements of the array1 from array2 if we call removeAll() function from array2 and array1 as a parameter.
Array elements can be deleted using the JavaScript operator delete . Using delete leaves undefined holes in the array. Use pop() or shift() instead.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With