Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Multiple Items from Array using underscore.js?

I have this:

var arrA = [{id:1,name:'a'},{id:2,name:'b'},{id:3,name:'c'}];

I have another array:

var arrB = [{id:1,other:'c'},{id:3,other:'d'}];

How can I remove the items from arrA that have property id same as arrB using underscore.js?

The expected result should be:

arrA = [{id:2, name:'b'}];

Thanks,

like image 378
Vicheanak Avatar asked Jan 05 '23 13:01

Vicheanak


2 Answers

Using Array#filter and Array#findIndex

var output = arrA.filter((el) => {
  return arrB.findIndex((elem) => {
    return elem.id == el.id;
  }) == -1;
});

One liner:

arrA.filter((el) => (arrB.findIndex((elem) => (elem.id == el.id)) == -1));

var arrA = [{
  id: 1,
  name: 'a'
}, {
  id: 2,
  name: 'b'
}, {
  id: 3,
  name: 'c'
}];


var arrB = [{
  id: 1,
  other: 'c'
}, {
  id: 3,
  other: 'd'
}];

var op = arrA.filter(function(el) {
  return arrB.findIndex(function(elem) {
    return elem.id == el.id;
  }) == -1;
});
console.log(op);

Or using Array#find

var arrA = [{
  id: 1,
  name: 'a'
}, {
  id: 2,
  name: 'b'
}, {
  id: 3,
  name: 'c'
}];


var arrB = [{
  id: 1,
  other: 'c'
}, {
  id: 3,
  other: 'd'
}];

var op = arrA.filter(function(el) {
  return !arrB.find(function(elem) {
    return elem.id == el.id;
  });
});
console.log(op);
like image 83
Rayon Avatar answered Jan 18 '23 19:01

Rayon


Like this

var arrA = [{id:1,name:'a'},{id:2,name:'b'},{id:3,name:'c'}];
var arrB = [{id:1,other:'c'},{id:3,other:'d'}];
var keys = _.keys(_.indexBy(arrB, "id"));
var result = _.filter(arrA, function(v) {
   return !_.contains(keys, v.id.toString());
});
console.log(result)

Hope this helps.

like image 41
Mykola Borysyuk Avatar answered Jan 18 '23 18:01

Mykola Borysyuk