Reorganize array elements into groups based on two attributes
P粉364642019
P粉364642019 2023-09-13 10:33:54
0
1
542

I have an array as follows:

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 want to regroup according to the same id-serial pair. {"id":"X", "serial":"Y"} and {"id":"Y", "serial":"X"} should be considered the same pair.

The expected results are as follows:

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 do I implement this?

P粉364642019
P粉364642019

reply all(1)
P粉163465905

Can't think of a better way to do this. One way is to group by unique key. Here, the unique key will be A|B, for both combinations {"id":"A", "serial":"B"} and {"id ":"A", "serial":"B"}

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)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!