【问题标题】:How can I find (& de-duplicate) combinations of an array of objects in Javascript?如何在 Javascript 中找到(和去重)对象数组的组合?
【发布时间】:2021-04-08 15:36:07
【问题描述】:

我在 Javascript 中有一个对象映射数组,如下所示:

Mapping_Array = [
    { input1: node_0, input2: node_1 },
    { input1: node_1, input2: node_2 },
    { input1: node_2, input2: node_3 },
    { input1: node_0, input2: node_1 },
    { input1: node_1, input2: node_0 }
];

我能够删除具有相同 input1 和 input2 的那些(例如上面的第一个条目和第 4 个条目),但我似乎无法找到并删除那些有 switched 条目(例如上面的第一个条目和最后一个条目)。我已经搜索过,但在 SO 上找不到任何具有类似答案的内容。有没有人遇到过这个问题并找到了解决方案?

编辑:添加我当前的函数来检查重复项:

function check_mapping_array() {
    // De-duplicate the array
    jsonObject = Mapping_Array.map(JSON.stringify);

    uniqueSet = new Set(jsonObject);
    Mapping_Array = Array.from(uniqueSet).map(JSON.parse);
}

【问题讨论】:

  • 您能否也显示您当前的代码以了解您是如何检查/删除的?那会很有帮助。
  • @Tigger,我已经添加了我上面的去重功能。
  • 节点是什么数据类型?
  • 一般来说,为您的对象找到一个规范的表示,例如按节点 ID 排序的输入。
  • @Bergi,节点都是字符串。

标签: javascript arrays object duplicates unique


【解决方案1】:

假设节点的数据类型是字符串或数字。 更新的答案: 使用 input1 和 input2 作为键并将索引存储为值

let map = new Map();

let arr = [
  { input1: "node_0", input2: "node_1" },
  { input1: "node_1", input2: "node_2" },
  { input1: "node_2", input2: "node_3" },
  { input1: "node_0", input2: "node_1" },
  { input1: "node_1", input2: "node_0" }
];

map.set(arr[0]["input1"] + "|" + arr[0]["input2"], 0);

for(let i=1; i<arr.length;i++){
  let temp = map.get(arr[i]["input2"] + "|" + arr[i]["input1"]);

  if(temp != undefined){//switch exists
    console.log("current index",i);
    console.log("prev index", temp);
    //now you remove the previous entry as well
  }
  else{
    map.set(arr[i]["input1"] + "|" + arr[i]["input2"], i);
  }
}  

对于其他数据类型,您始终可以使用 JSON.stringify

【讨论】:

  • 这真的很接近...你把//remove entry at index i 放在哪里,我用arr.splice(i,1); 替换了它但是,你知道如何替换other 条目吗?例如已经在 arr 中的那个?
  • 我已经更新了答案。使用它,您可以访问两个条目的索引
猜你喜欢
  • 2021-03-11
  • 2019-04-28
  • 1970-01-01
  • 1970-01-01
  • 2018-07-31
  • 1970-01-01
  • 2018-12-18
  • 2010-11-10
  • 2017-07-05
相关资源
最近更新 更多