-2

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!

fadsgas
  • 17
  • 4
  • You could convert this to a structure `{[teamName]: SetOfPlayerIds}` and convert it back to your structure. – jabaa Jul 22 '22 at 13:39
  • Does this answer your question? [How to remove all duplicates from an array of objects?](https://stackoverflow.com/questions/2218999/how-to-remove-all-duplicates-from-an-array-of-objects) – Rafi Jul 25 '22 at 11:42

1 Answers1

0

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, { teamName, playerId }) => {
  if (!acc.hasOwnProperty(teamName)) acc[teamName] = new Set();
  acc[teamName].add(playerId);
  return acc;
}, {})).flatMap(([teamName, playerIds]) => Array.from(playerIds).map(playerId => ({ teamName, playerId })));

console.log(result);
jabaa
  • 5,844
  • 3
  • 9
  • 30