1

I want to sort array

var highscores = [
{Username: "joba_gm11", Score: "20"},
{Username: "nika.jobava45", Score: "20"},
{Username: "trollgamer481", Score: "100"},
{Username: "Gimira", Score: "20"},
{Username: "dirtytank481", Score: "50"},
];

with this code:

for (var i = 0; i < highscores; i++) {
    for (var j = 0; j < highscores; j++) {
        if (highscores[i].Score < highscores[j].Score) {
            var temp = highscores[i];
            highscores[i] = highscores[j];
            highscores[j] = temp;
        }
    }
}

but it doesn't work. any ideas?

0

2 Answers 2

1

You might need to convert the scores to numbers before comparing them. Comparing them as strings compares them alphabetically.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use + to convert a string into a number in javascript.

Assuming you are trying to implement Bubble sort, with your current code:

const highscores  = [
    {
        "Username": "joba_gm11",
        "Score": "20"
    },
    {
        "Username": "nika.jobava45",
        "Score": "20"
    },
    {
        "Username": "trollgamer481",
        "Score": "100"
    },
    {
        "Username": "Gimira",
        "Score": "20"
    },
    {
        "Username": "dirtytank481",
        "Score": "50"
    }
];


let sorted = false;
while (!sorted) {
    sorted = true;
    for (let i = 1; i < highscores.length; i++) {
        if (+highscores[i - 1].Score > +highscores[i].Score) {
            sorted = false;
            let temp = highscores[i - 1];
            highscores[i - 1] = highscores[i];
            highscores[i] = temp;
        }
    }
}

console.log(highscores);

If you are allowed to use the much more efficient inbuilt sort:

const highscores  = [
    {
        "Username": "joba_gm11",
        "Score": "20"
    },
    {
        "Username": "nika.jobava45",
        "Score": "20"
    },
    {
        "Username": "trollgamer481",
        "Score": "100"
    },
    {
        "Username": "Gimira",
        "Score": "20"
    },
    {
        "Username": "dirtytank481",
        "Score": "50"
    }
];

highscores.sort((a, b) => +a.Score - (+b.Score));

console.log(highscores);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.