How to compare two arrays, and return the name of the array with highest value in a certain index

Ask a question+

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

abdokb 40

You save the score using bad structure. Try using one dynamic array only.

add comment

1 Answer


If you store all that data in just one array it will be a lot easier to get the answer you want, even if you had 100 items you wanted to find the answer of.

// Either store it like the following
var player1 = new Array [1, "billy"]; // You would actually say var player1 = [1, "billy"];
var player2 = new Array [2, "jean"]; // Again, say var player2 = [2, "jean"];
var checkArray = [player1,player2];

// Or store it all in one to start with
var arrayToCheck = [[1, "billy"], [2, "jean"]];

// It also can be easier to use parameters
function checkWinner(thisArray) {
    // Reduce the array to only the set with the largest value
    var winner = thisArray.reduce((n1, n2) => {return n1[0] > n2[0] ? n1 : n2});
    /* The above function checks the first index of the array and sees which is bigger and then continues...
       which means you could have (technically) an infinite number of sets and it would still work */

checkWinner(checkArray); // Here you could use either checkArray or arrayToCheck

You could also do it this way:

// Either store it like the following
var player1 = [1, "billy"];
var player2 = [2, "jean"];

// Using the arguments object, you can access all parameters even when you don't specify them
function checkWinner(...args) {
    var maxVal = args[0]; // Initialize maxVal to the first value
    for (var i = 1; i<args.length; i++) {
        if (args[i][0] > maxVal[0]) {
            maxVal = args[i]; // If it is greater change maxVal to the bigger one
    console.log(maxVal[1]); // Print winner

checkWinner(player1, player2); // Here you could add as many parameters as you needed

If there is anything that you would like me to clarify, let me know.

Dark Vortex 0
add comment

Your Answer