13

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]
1
  • 2
    Do you mean b[] = [2,3] ? To have what you expected as a[] = [1,4]. Commented Jul 17, 2019 at 4:21

5 Answers 5

16

I would use the filter method:

a = a.filter(function (item) {
    return b.indexOf(item) === -1;
});
Sign up to request clarification or add additional context in comments.

2 Comments

Shouldn't it be: return b.indexOf(item) == -1;
@Kolby thanks for the correction. The closing parentheses must be after item and the comparson operator should be === instead of !==
4
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);

Comments

2

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.

Comments

2

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);
   }
}

4 Comments

array.prototype.forEach - new in ECMAScript5 (ie not <=IE8): developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
@freedomn-m is right .forEach is ECMAScript5 so you either need to transpile, use a library that has a forEach method, or just use a for loop. The logic remains the same.
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); } }
Added IE8. Thanks @Aruna
0
function myFunction(a, b) {
  return a.filter(item => b.indexOf(item) < 0)
}

console.log(myFunction([1, 2, 3], [1, 2]))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.