[英]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? 如何使用underscore.js从arrA中删除属性ID与arrB相同的项目?
The expected result should be: 预期结果应该是:
arrA = [{id:2, name:'b'}];
Thanks, 谢谢,
Using
Array#filter
andArray#findIndex
使用Array#filter
和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
或者使用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. 希望这可以帮助。
In pure javascript you can use forEach()
loop and splice()
to remove object if it's id
is found in other array. 在纯javascript中,如果在其他数组中找到了id
则可以使用forEach()
循环和splice()
来删除对象。
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 b = arrB.map(e => e.id); arrA.forEach(function(e, i) { if(b.indexOf(e.id) != -1) arrA.splice(i, 1); }); console.log(arrA);
Sounds like you want the difference, but unfortunately that won't work for objects. 听起来你想要有所不同,但不幸的是,它不适用于对象。 Instead you could try this: 相反,你可以试试这个:
arrA = _.filter(arrA, function(obj){
return !_.findWhere(arrB, {id: obj.id});
});
You could do this without underscore using the build in filter and find functions. 您可以使用内置过滤器和查找函数,在没有下划线的情况下执行此操作。
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 res = arrB.reduce((acc, b) => { return acc.filter(({id}) => id !== b.id); }, arrA); // [{id:2,name:'b'}] console.log(res);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.