如何比较两个数组并通过完整迭代删除重复的对象

时间:2018-03-29 13:28:16

标签: javascript ecmascript-6 typescript2.0

我有两个对象数组,

TypeError: db.collection(...).find(...).where is not a function
at C:\chat\mongo.js:1898:14
at connectCallback (C:\Users\Srinu\AppData\Roaming\npm\node_modules\mongodb\lib\mongo_client.js:515:5)
at C:\Users\Srinu\AppData\Roaming\npm\node_modules\mongodb\lib\mongo_client.js:430:11
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)

当我尝试使用以下逻辑比较和迭代两个数组时,

var deSelectedRows = [
{ PoHeaderKey: 129, OrderNo: "WS1", LineNo: 1, id: "BRIC01"},
{ PoHeaderKey: 129, OrderNo: "WS1", LineNo: 1, id: "BRIC02"},
{ PoHeaderKey: 129, OrderNo: "WS1", LineNo: 1, id: "BRIC03"},
{ PoHeaderKey: 129, OrderNo: "WS1", LineNo: 1, id: "BRIC04"}
];

var selectedRows = [
{ PoHeaderKey: 129, OrderNo: "WS1", LineNo: 1, id: "BRIC01"},
{ PoHeaderKey: 129, OrderNo: "WS1", LineNo: 1, id: "BRIC02"},
{ PoHeaderKey: 129, OrderNo: "WS1", LineNo: 1, id: "BRIC03"},
{ PoHeaderKey: 129, OrderNo: "WS1", LineNo: 1, id: "BRIC04"}
];

由于所选行正在拼接,我无法完全迭代。 请帮帮我。

3 个答案:

答案 0 :(得分:2)

您可以对给定的id使用Set,并使用该集合过滤selectedRows



var deSelectedRows = [{ PoHeaderKey: 129, OrderNo: "WS1", LineNo: 1, id: "BRIC01"}, { PoHeaderKey: 129, OrderNo: "WS1", LineNo: 1, id: "BRIC02"}, { PoHeaderKey: 129, OrderNo: "WS1", LineNo: 1, id: "BRIC03"}, { PoHeaderKey: 129, OrderNo: "WS1", LineNo: 1, id: "BRIC04"}],
    selectedRows = [{ PoHeaderKey: 129, OrderNo: "WS1", LineNo: 1, id: "BRIC01"}, { PoHeaderKey: 129, OrderNo: "WS1", LineNo: 1, id: "BRIC02"}, { PoHeaderKey: 129, OrderNo: "WS1", LineNo: 1, id: "BRIC03"}, { PoHeaderKey: 129, OrderNo: "WS1", LineNo: 1, id: "BRIC04"}],
    ids = new Set(deSelectedRows.map(({ id }) => id));

selectedRows = selectedRows.filter(({ id }) => !ids.has(id));

console.log(selectedRows);




答案 1 :(得分:1)

为避免突变问题,您需要从最后一个元素循环,因为主要问题是访问过的元素。

{{1}}

答案 2 :(得分:0)

您可以使用filter来实现此功能。



var deSelectedRows = [
{ PoHeaderKey: 129, OrderNo: "WS1", LineNo: 1, id: "BRIC01"},
{ PoHeaderKey: 129, OrderNo: "WS1", LineNo: 1, id: "BRIC02"},
{ PoHeaderKey: 129, OrderNo: "WS1", LineNo: 1, id: "BRIC03"},
{ PoHeaderKey: 129, OrderNo: "WS1", LineNo: 1, id: "BRIC04"}
];

var selectedRows = [
{ PoHeaderKey: 129, OrderNo: "WS1", LineNo: 1, id: "BRIC01"},
{ PoHeaderKey: 129, OrderNo: "WS1", LineNo: 1, id: "BRIC02"},
{ PoHeaderKey: 129, OrderNo: "WS1", LineNo: 1, id: "BRIC03"},
{ PoHeaderKey: 129, OrderNo: "WS1", LineNo: 1, id: "BRIC04"},
{ PoHeaderKey: 129, OrderNo: "WS1", LineNo: 1, id: "BRIC05"}
];

selectedRows= selectedRows.filter(function(cv){
    return !deSelectedRows.find(function(e){
        return e.id == cv.id;
    });
});

console.log(selectedRows);