1

For example I have two arrays like this.

const data = ["John", "Andy", "Ruby"]
const eliminator = ["John"]

So I expect a result like :

data = ["Andy", "Ruby"]

I'm so new with javascript. It would be appreciated if the answer is in plain javascript, but advanced answer are very welcome. Thank you

rzelegra
  • 13
  • 4

4 Answers4

1

Use Array.filter() to filter the values of data array that do not present in eliminator array.

const data = ["John", "Andy", "Ruby"]
const eliminator = ["John"]
var res = data.filter(name => eliminator.indexOf(name) === -1);
console.log(res);

You can use the simple function declarations if you expect it to work in all browsers. Also note that you need to use indexOf() and not includes() method as includes() do not work in IE browsers.

const data = ["John", "Andy", "Ruby"]
const eliminator = ["John"]
var res = data.filter(function(name){
   return eliminator.indexOf(name) === -1;
});
console.log(res);

For further reading you can refer here: Array.filter()

Ankit Agarwal
  • 28,439
  • 5
  • 29
  • 55
  • 1
    I'm not a downvoter : ) I just want to add that OP question have the tag nodejs so I think the issue with IE browsers and `includes()` doesn't matters. nodejs supports `includes()` from version 6.0.0. – Emeeus Aug 23 '18 at 13:30
  • @Emeeus yes, that does not but there are several cases when OP tags Nodejs but they also tend to use as in front end HTML page. – Ankit Agarwal Aug 23 '18 at 13:34
0

If you use this functionality all over the project, You can add the diff prototype in array class.

Array.prototype.diff = function(eli) {
   return this.filter(function(i) {return eli.indexOf(i) < 0;});
};

After that you can use this method any where...

data.diff(eliminator) 

Gives you the required result.

mukesh kudi
  • 709
  • 5
  • 18
0

Using filter() and includes() (that returns true or false) makes the code shorter.

const data = ["John", "Andy", "Ruby"]
const eliminator = ["John"]

var newData = data.filter(o=>!eliminator.includes(o))

console.log(newData)
Emeeus
  • 4,104
  • 2
  • 14
  • 32
0

You can use Underscore.js _.difference()

const data = ["John", "Andy", "Ruby"];
const eliminator = ["John"];

var NewData = _.difference(data , eliminator);

// Result : NewData = ["Andy", "Ruby"]
cfnerd
  • 3,198
  • 12
  • 28
  • 39
Lee
  • 78
  • 2
  • 13