Compare multiple arrays of objects and convert them into single objects by getting the unique object help of id value using javascript
const data= [
[{name:x , id:1},{name:a , id:13},{name:a , id:14},{name:a , id:15},{name:a , id:16},],
[{name:y , id:12},{name:a , id:13},{name:a , id:14},{name:a , id:15},{name:a , id:16},],
[{name:z , id:22},{name:a , id:13},{name:a , id:14},{name:a , id:15},{name:a , id:16},]
]
the expected output is:
const out= [
{name:a , id:1}, {name:b , id:12}, {name:b , id:22}
]
I have multiple arrays of objects compare all and get the unique objects into a single array using javascript
>Solution :
- Using
Array#flat, convert the 2d array into one - Using
Array#reduce, iterate over the latter while updating aMapwhere the id is thekeyand the count is thevalue - Using
Map#entries, get the list of id-count pairs from the Map. Then, usingArray#filter, get the ids whose count is 1. Finally, usingArray#map, get the list of resulting ids - Using
Array#filter, iterate over the flattened array of objects and return the elements whose ids belong to the non-repeating ids list
const data = [
[ { name: 'x', id: 1 }, { name: 'a', id: 13 }, { name: 'a', id: 14 }, { name: 'a', id: 15 }, { name: 'a', id: 16 } ],
[ { name: 'y', id: 12 }, { name: 'a', id: 13 }, { name: 'a', id: 14 }, { name: 'a', id: 15 }, { name: 'a', id: 16 } ],
[ { name: 'z', id: 22 }, { name: 'a', id: 13 }, { name: 'a', id: 14 }, { name: 'a', id: 15 }, { name: 'a', id: 16 } ]
];
const arr = data.flat();
const idCountMap = arr.reduce((map, { id }) => map.set(id, (map.get(id) ?? 0) + 1), new Map);
const nonRepeatingIds =
[...idCountMap.entries()]
.filter(([ id, count ]) => count === 1)
.map(([ id ]) => id);
const nonRepeatingItems = arr.filter(({ id }) => nonRepeatingIds.includes(id));
console.log(nonRepeatingItems);