如何在 Javascript 中找到(并删除重复项)对象数组的组合?
How can I find (& de-duplicate) combinations of an array of objects in Javascript?
我在 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 }
];
我能够删除具有相同输入 1 和输入 2 的那些(例如上面的第一个条目和第四个条目),但我似乎无法找到并删除那些具有 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);
}
假设节点的数据类型是字符串或数字。
更新的答案:
使用 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
我在 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 }
];
我能够删除具有相同输入 1 和输入 2 的那些(例如上面的第一个条目和第四个条目),但我似乎无法找到并删除那些具有 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);
}
假设节点的数据类型是字符串或数字。 更新的答案: 使用 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