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?
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)