基于两个属性重新分组数组元素

huangapple go评论61阅读模式
英文:

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 = [
{&quot;id&quot;:&quot;A&quot;, &quot;serial&quot;:&quot;C&quot;},
{&quot;id&quot;:&quot;A&quot;, &quot;serial&quot;:&quot;E&quot;},
{&quot;id&quot;:&quot;A&quot;, &quot;serial&quot;:&quot;B&quot;},
{&quot;id&quot;:&quot;A&quot;, &quot;serial&quot;:&quot;B&quot;},
{&quot;id&quot;:&quot;B&quot;, &quot;serial&quot;:&quot;A&quot;},
{&quot;id&quot;:&quot;B&quot;, &quot;serial&quot;:&quot;C&quot;},
{&quot;id&quot;:&quot;C&quot;, &quot;serial&quot;:&quot;B&quot;},
{&quot;id&quot;:&quot;C&quot;, &quot;serial&quot;:&quot;F&quot;}
]

const res = Object.values(array1.reduce((acc, curr) =&gt; {
  const k = [curr.id, curr.serial].sort().join(&#39;|&#39;);
  (acc[k] ??= []).push(curr);
  return acc;
}, {}));


console.log(res)

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年4月6日 19:35:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/75949055.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定