Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript remove array from array

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.

like image 213
David Weng Avatar asked Oct 06 '11 01:10

David Weng


People also ask

How do you remove an array from an array?

You can use unset() function which removes the element from an array and then use array_values() function which indexes the array numerically.

How do you remove an element from an array in JavaScript?

Array elements can be deleted using the JavaScript operator delete . Using delete leaves undefined holes in the array. Use pop() or shift() instead.

How do you remove an object from an array?

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.

How do you remove indices from an array?

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.


2 Answers

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.

like image 93
icktoofay Avatar answered Sep 19 '22 23:09

icktoofay


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);
like image 40
Mohammad Usman Avatar answered Sep 23 '22 23:09

Mohammad Usman