Rayan Slim Rayan Slim - 12 days ago 5
Javascript Question

Filter an array of strings from another array of strings in javascript (this is not a duplicate)

I have an array:

['Bobby', 'John', 'Sam']
, and another simply
['Bobby', 'John']
. I want to filter The second array from the first, leaving only
Sam
. I'm trying to achieve this with
filter
.

Answer

Use Array#filtermethod with Array#indexOf method:

var a = ['Bobby', 'John', 'Sam'],
  b = ['Bobby', 'John'];

var res = a.filter(function(v) {
  return b.indexOf(v) == -1;
  // or in latest browser
  // return !b.includes(v);
})

console.log(res);

This works because Array#filter takes a callback that is a predicate, and filters elements of an array based on that callback. If the callback returns true, the element is kept, otherwise it is filtered out. Per the documentation:

callback

Function is a predicate, to test each element of the array. Return true to keep the element, false otherwise

In the snippet above, v holds the value for the current value being processed in the array. The code then goes through the a array, returning true or false based on if that element (v) appears in b, with Array#indexOf.

Since Array#indexOf returns -1 if the element does not exist in the array, the callback checks to see if v does not exist in b. If it does not, filter it out, thus giving the desired result.

Comments