Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]
like image 665
himanshu saini Avatar asked Oct 13 '16 21:10

himanshu saini


People also ask

How do you remove all elements from one array from another array?

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.

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.


3 Answers

I would use the filter method:

a = a.filter(function (item) {
    return b.indexOf(item) === -1;
});
like image 191
Barry127 Avatar answered Oct 19 '22 13:10

Barry127


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);
like image 3
zdd Avatar answered Oct 19 '22 11:10

zdd


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.

like image 2
Tyler Burki Avatar answered Oct 19 '22 11:10

Tyler Burki