0

I have been working on the scoring system for a game I am building with Javascript and have run into a problem. I am trying to compare the index 0 of a couple of arrays and return the index 1 of the array with the highest value.

This is what I have so far:

var player1 = new Array [1, "billy"];
var player2 = new Array [2, "jean"];

function checkWinner() {
    var winner = Math.max(player1[0], player2[0]);
    console.log(winner[1]);
}

checkWinner();
  • You can't use `new Array []` to instantiate arrays. Use `new Array()` or `[]`. [Here's the difference](https://stackoverflow.com/q/931872/8289918). – cherryblossom May 05 '20 at 00:00

4 Answers4

1

I really like reduce as an option here. It goes through each of the players 1 by 1 and if the current player has a higher score than the previous player, then the current player has the highest score (and at the end will be the winner).

const players = [
  {
    name: "billy",
    score: 3
  },
  {
    name: "jean",
    score: 2
  }
];

const getWinner = players => players.reduce((currentWinner, player) => 
  player.score > currentWinner.score ? player : currentWinner
)
const winner = getWinner(players)
console.log(`The winner is: ${winner.name}!`)

I also changed the array of (score, name) to be an object with keys "score" and "name" to be able to reference those values later with out brackets.

jshawl
  • 2,828
  • 2
  • 19
  • 31
0

In your code the variable winner will be an integer that is the larger of the 2 scores. It's not an array that you can get index 1 from. You want to get the player Array that has the higher score, not the score itself. You can do that like this:

function checkWinner() {
    var winner = player1;
    if (player1[0] < player2[0]) {
        winner = player2;
    }
    console.log(winner[1]);
}

This doesn't handle the case where there is a tie, but you can add an if-statement for that also.

Always Learning
  • 4,633
  • 2
  • 13
  • 30
0

You can do a simple if:

function checkWinner() {
var winner;
if (player1[0] < player2[0]) {
    winner = player2;
}else{
    winner = player1;
}

console.log(winner[1]);

}

Jacopo Mosconi
  • 228
  • 2
  • 12
0

Bonus: check the winner of any number of players:

var player1 = [1, "billy"];
var player2 = [2, "jean"];

function checkWinner() {
    var players = Array.prototype.slice.call(arguments);
    var max = Math.max.apply(null, players.map(function (p) {
        return p[0];
    }));
    var winner = players.filter(function (p) {
        return p[0] === max;
    })[0];
    console.log(winner[1]);
}

checkWinner(player1, player2);

ES2015:

const player1 = [1, "billy"];
const player2 = [2, "jean"];

const checkWinner = (...players) => {
    const max = Math.max(...players.map(p => p[0]));
    const winner = players.find(p => p[0] === max);
    console.log(winner[1]);
}

checkWinner(player1, player2);
cherryblossom
  • 5,523
  • 2
  • 15
  • 39