Looping through an array of objects.. how can I filter out duplicate names and return players in a new array?

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


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

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