Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Compare multiple arrays of objects using java script

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

  • Using Array#flat, convert the 2d array into one
  • Using Array#reduce, iterate over the latter while updating a Map where the id is the key and the count is the value
  • Using Map#entries, get the list of id-count pairs from the Map. Then, using Array#filter, get the ids whose count is 1. Finally, using Array#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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading