2

I'm trying to iterate over an array of objects, and in a new array, return only the players, their names in the same order and not listed more than once.. Was thinking I could do something similar to this or with a forEach loop but I'm not really sure how to tackle the multiple occurrences

const players = function(outcomes) {

  const arr = [];
  for (let i = 0; i < outcomes.length; i++) {
    if (outcomes.includes(winner, loser))
    arr.push(arr[i]);
  }
  return arr;

};

Example Input and Expected Output:

const playerNames = [
 { winner: 'Sam',   loser: 'Bruce',    loser_points: 10 },
  { winner: 'Sam',   loser: 'Hakim',  loser_points: 9 }]

Output I want: [Sam, Bruce, Hakim]
steph
  • 35
  • 4
  • Does this answer your question? [Remove duplicate values from JS array](https://stackoverflow.com/questions/9229645/remove-duplicate-values-from-js-array) – mo3n Jan 18 '22 at 05:51

4 Answers4

2
const playerNames = [
    { winner: 'Sam',   loser: 'Bruce',    loser_points: 10 },
    { winner: 'Sam',   loser: 'Hakim',  loser_points: 9 }
];

var getPlayers = function(games) { 
    var players = {}; 
    var game;
    for (var i=0; i<games.length; i++) {
        game = games[i];
        players[game.winner] = 1;
        players[game.loser] = 1;
    }
    return Object.keys(players);
}

console.log(getPlayers(playerNames));

Elaine Alt
  • 56
  • 4
1

Use Set to generate unique list of data.

const playerNames = [{ winner: 'Sam', loser: 'Bruce', loser_points: 10 },{ winner: 'Sam', loser: 'Hakim', loser_points: 9 }];
const players = Array.from(new Set(playerNames.flatMap((node) => [node.winner, node.loser])));
console.log(players);
Nitheesh
  • 19,238
  • 3
  • 22
  • 49
1

There are multiple ways to achieve this (please see other solutions posted). Below is a modified version of your code. Some minor corrections added in your if condition.

const playerNames = [{
    winner: 'Sam',
    loser: 'Bruce',
    loser_points: 10
  },
  {
    winner: 'Sam',
    loser: 'Hakim',
    loser_points: 9
  },
  {
    winner: 'Sam',
    loser: 'Paul',
    loser_points: 9
  }
];

const players = function(outcomes) {

  const arr = [];
  for (let i = 0; i < outcomes.length; i++) {
    // check and push winner
    if (!arr.includes(outcomes[i].winner))
      arr.push(outcomes[i].winner);

    // check and push loser
    if (!arr.includes(outcomes[i].loser))
      arr.push(outcomes[i].loser);
  }
  return arr;

};


console.log(players(playerNames));
kiranvj
  • 32,342
  • 7
  • 71
  • 76
0

I updated my answer based on Elaine Alt one, because I really liked his/her approach!

(but using reduce instead)

const getNames = games => {
    return Object.keys(
        games.reduce((acc, game) => {
            return {
                ...acc,
                [game.winner]: 1,
                [game.loser]: 1,
            };
        }, {})
    );
};
maxpsz
  • 431
  • 3
  • 9