我有2个对象阵列 ARRAY1:
[{ id: 2, ref: 1010101 },
{ id: 2, ref: 1010107 }]
ARRAY2:
[{ id: 2, ref: 10010001 },
{ id: 2, ref: 10010002 },
{ id: 2, ref: 10010003 },
{ id: 2, ref: 10010006 },
{ id: 2, ref: 10010007 },
{ id: 2, ref: 10010008 },
{ id: 2, ref: 10010009 },
{ id: 2, ref: 10020005 },
{ id: 2, ref: 1010101 }]
我需要完成两项任务:
1.找到 array1 的哪些元素位于 array2 中。找到物品后,我会用这些元素做点什么
2.删除从 array2 中找到的元素。在我对找到的项目执行某些操作后,我需要删除找到的每个项目。
我试图用lodash来做,但没有成功。
我需要这样的东西:
if(elementFound) {
//do something
doSomething(item);
//after it, remove from array2
removeItemFromArray2(item);
}
谢谢,我认为使用lodash可以轻松实现这一目标。
答案 0 :(得分:2)
尝试在此上下文中使用Array.prototype.filter
来实现您想要的目标,
var filteredArray = Array2.filter(function(itm){
return Array1.filter(function(itmIn){
return itmIn.id === itm.id && itmIn.ref === itm.ref;
}).length == 0;
});
答案 1 :(得分:2)
有一个特定的lodash功能:
var array1 = [
{ id: 2, ref: 1010101 },
{ id: 2, ref: 1010107 }
];
var array2 = [
{ id: 2, ref: 10010001 },
{ id: 2, ref: 10010002 },
{ id: 2, ref: 10010003 },
{ id: 2, ref: 10010006 },
{ id: 2, ref: 10010007 },
{ id: 2, ref: 10010008 },
{ id: 2, ref: 10010009 },
{ id: 2, ref: 10020005 },
{ id: 2, ref: 1010101 }
];
var res = _.differenceBy(array2, array1, 'ref');
document.write("<pre>" + JSON.stringify(res, null, 3) + "</pre>")
<script src="https://cdn.jsdelivr.net/lodash/4.6.1/lodash.min.js"></script>
答案 2 :(得分:1)
_.remove
以编程方式从array2
中删除元素。在您的情况下,该谓词将是“array1
”中的元素,
var array1 = [{ id: 2, ref: 1010101 },
{ id: 2, ref: 1010107 }]
var array2 = [{ id: 2, ref: 10010001 },
{ id: 2, ref: 10010002 },
{ id: 2, ref: 10010003 },
{ id: 2, ref: 10010006 },
{ id: 2, ref: 10010007 },
{ id: 2, ref: 10010008 },
{ id: 2, ref: 10010009 },
{ id: 2, ref: 10020005 },
{ id: 2, ref: 1010101 }]
_.remove(array2, function (item) {
return _.find(array1, item);
});
document.write("<pre>" + JSON.stringify(array2, null, 2) + "</pre>")
<script src="https://cdn.jsdelivr.net/lodash/4.6.1/lodash.min.js"></script>
答案 3 :(得分:1)
具有线性O的解决方案。
var array1 = [{ id: 2, ref: 1010101 }, { id: 2, ref: 1010107 }],
array2 = [{ id: 2, ref: 10010001 }, { id: 2, ref: 10010002 }, { id: 2, ref: 10010003 }, { id: 2, ref: 10010006 }, { id: 2, ref: 10010007 }, { id: 2, ref: 10010008 }, { id: 2, ref: 10010009 }, { id: 2, ref: 10020005 }, { id: 2, ref: 1010101 }],
result = function (a, b) {
function k(x) { return x.id + '|' + x.ref; }
var o = {};
b.forEach(function (c) {
o[k(c)] = true;
});
a.forEach(function (c) {
o[k(c)] = false;
});
return b.filter(function (c) {
return o[k(c)];
});
}(array1, array2);
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
&#13;