Home  >  Q&A  >  body text

Reorganize array elements into groups based on two attributes

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粉364642019P粉364642019371 days ago573

reply all(1)I'll reply

  • P粉163465905

    P粉1634659052023-09-14 10:04:41

    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)

    reply
    0
  • Cancelreply