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!
>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);