Heim > Fragen und Antworten > Hauptteil
Ich habe ein Array wie dieses:
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"} ]
Ich möchte nach denselben ID-Serien-Paaren neu gruppieren. {"id": "X", "serial": "Y"} und {"id": "Y", "serial": "X"} sollten als dasselbe Paar betrachtet werden.
Die erwarteten Ergebnisse sind wie folgt:
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"}] ]
Wie setze ich das um?
P粉1634659052023-09-14 10:04:41
无法想到更好的方法来做这个。一种方法是按照唯一键进行分组。在这里,唯一键将是A|B
,对于两个组合{"id":"A", "serial":"B"}
和{"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)