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,
Using
Array#filter
andArray#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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With