英文:
Regrouping array elements based on two attributes
问题
我有一个类似这样的数组:
let array1 = [
{ "id": "A", "serial": "C" },
{ "id": "A", "serial": "E" },
{ "id": "A", "serial": "B" },
{ "id": "A", "serial": "B" },
{ "id": "B", "serial": "A" },
{ "id": "B", "serial": "C" },
{ "id": "C", "serial": "B" },
{ "id": "C", "serial": "F" }
]
我想要按相同的id-serial对进行分组。{ "id": "X", "serial": "Y" } 和 { "id": "Y", "serial": "X" } 应被视为相同的对。
预期的结果如下:
let res = [
[{ "id": "A", "serial": "C" }],
[{ "id": "A", "serial": "E" }],
[{ "id": "A", "serial": "B" }, { "id": "A", "serial": "B" }, { "id": "B", "serial": "A" }],
[{ "id": "B", "serial": "C" }, { "id": "C", "serial": "B" }],
[{ "id": "C", "serial": "F" }]
]
如何实现这个目标?
英文:
I have an array such as this one :
let array1 = [
{"id":"A", "serial":"C"},
{"id":"A", "serial":"E"},
{"id":"A", "serial":"B"},
{"id":"A", "serial":"B"},
{"id":"B", "serial":"A"},
{"id":"B", "serial":"C"},
{"id":"C", "serial":"B"},
{"id":"C", "serial":"F"}
]
I would like to regroup by same id-serial pairs. {"id":"X", "serial":"Y"} and {"id":"Y", "serial":"X"} should be considered same pairs.
As an expected result :
let res = [
[{"id":"A", "serial":"C"}],
[{"id":"A", "serial":"E"}],
[{"id":"A", "serial":"B"},{"id":"A", "serial":"B"},{"id":"B", "serial":"A"}],
[{"id":"B", "serial":"C"},{"id":"C", "serial":"B"}],
[{"id":"C", "serial":"F"}]
]
How can I acchieve this?
答案1
得分: 2
这是您提供的代码部分,无需翻译。如果您需要有关代码的进一步解释或帮助,请随时告诉我。
英文:
couldn't think of a better way to do this. one approach would be to group by a unique key. here a unique key would A|B
for both combinations {"id":"A", "serial":"B"}
and {"id":"A", "serial":"B"}
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
let array1 = [
{"id":"A", "serial":"C"},
{"id":"A", "serial":"E"},
{"id":"A", "serial":"B"},
{"id":"A", "serial":"B"},
{"id":"B", "serial":"A"},
{"id":"B", "serial":"C"},
{"id":"C", "serial":"B"},
{"id":"C", "serial":"F"}
]
const res = Object.values(array1.reduce((acc, curr) => {
const k = [curr.id, curr.serial].sort().join('|');
(acc[k] ??= []).push(curr);
return acc;
}, {}));
console.log(res)
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论