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

How to remove some identical objects in array(js)?

I have an array of objects(like this)

[
{teamName: 'first', playerId: 316}
{teamName: 'first', playerId: 315}
{teamName: 'first', playerId: 316}
{teamName: 'first', playerId: 316}
{teamName: 'second', playerId: 315}
{teamName: 'second', playerId: 318}
{teamName: 'third', playerId: 318}
{teamName: 'third', playerId: 316}
]

And I need to write a function which removes some identical objects in array, and the output should be like this:

[
{teamName: 'first', playerId: 315}
{teamName: 'first', playerId: 316}
{teamName: 'second', playerId: 315}
{teamName: 'second', playerId: 318}
{teamName: 'third', playerId: 318}
{teamName: 'third', playerId: 316}
]

Thanks!

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 :

For really large arrays, you could convert this to a structure {[teamName]: SetOfPlayerIds} and convert it back to your structure. This approach has a better performance (O(n log n)) than comparing each element with each other (O(n²)).

const data = [{teamName: 'first', playerId: 316},{teamName: 'first', playerId: 315},{teamName: 'first', playerId: 316},{teamName: 'first', playerId: 316},{teamName: 'second', playerId: 315},{teamName: 'second', playerId: 318},{teamName: 'third', playerId: 318},{teamName: 'third', playerId: 316}];

const result = Object.entries(data.reduce((acc, el) => {
  if (!acc.hasOwnProperty(el.teamName)) acc[el.teamName] = new Set();
  acc[el.teamName].add(el.playerId);
  return acc;
}, {})).flatMap(([teamName, playerIds]) => Array.from(playerIds).map(playerId => ({ teamName, playerId })));

console.log(result);
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