Assume we have the following arrays:
a = [1, 2, 3, 4, 5]
and
b = [2, 3]
How can I subtract b from a? So that we have c = a - b
which should be equal to [1, 4, 5]
. jQuery solution would also be fine.
You can use unset() function which removes the element from an array and then use array_values() function which indexes the array numerically.
Array elements can be deleted using the JavaScript operator delete . Using delete leaves undefined holes in the array. Use pop() or shift() instead.
To remove an object from an array by its value:Call the findIndex() method to get the index of the object in the array. Use the splice() method to remove the element at that index. The splice method changes the contents of the array by removing or replacing existing elements.
Find the index of the array element you want to remove using indexOf , and then remove that index with splice . The splice() method changes the contents of an array by removing existing elements and/or adding new elements. The second parameter of splice is the number of elements to remove.
Assuming you're on a browser that has Array.prototype.filter
and Array.prototype.indexOf
, you could use this:
var c = a.filter(function(item) { return b.indexOf(item) === -1; });
If the browser in question does not have those methods, you may be able to shim them.
This is a modified version of the answer posted by @icktoofay.
In ES6 we can make use of:
Array.prototype.contains()
Array.prototype.filter()
Arrow functions
This will simplify our code to:
var c = a.filter(x => !b.includes(x));
Demo:
var a = [1, 2, 3, 4, 5]; var b = [2, 3]; var c = a.filter(x => !b.includes(x)); console.log(c);
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