Sorting Array Elements by variable (JavaScript Only)

Hello. I’ve made an text array and i can’t find any possible way to sort it’s elements by variable.
The text array is some kind of leaderboard and it goes like this:

var position : int = 1;
var username : String;
var highScore : int;
var myArray = new Array(ID, username, highScore);

The case is:


Position - Username - HighScore

1 - player1 - 315

1 - player2 - 684

1 - player3 - 426


What i am trying to do is sort these elements by HighScore and change ID to 1,2,3 based on it’s position in array. The results should look like this:


Position - Username - HighScore

1 - player2 - 684

2 - player3 - 426

3 - player1 - 315


Thanks.

You can create an struct for your player and than add all these players in an Array. Than all you need to do is to use Array.Sort and give a condition. Like this:

using UnityEngine;
using System.Collections;
using System;

public class PlayerInfo
{

    public int id;
    public string username;
    public int highscore;

    public PlayerInfo(int _id, string _username, int _highscore)
    {
        id = _id;
        username = _username;
        highscore = _highscore;
    }
}

public class PlayerHighScore : MonoBehaviour {

	// Use this for initialization
	void Start () {
        PlayerInfo p1 = new PlayerInfo(0, "Fred", 10000);
        PlayerInfo p2 = new PlayerInfo(1, "Bob", 9999);
        PlayerInfo p3 = new PlayerInfo(2, "Peter", 34);

        PlayerInfo[] allPlayers = new PlayerInfo[3] { p1, p2, p3 };

        Array.Sort(allPlayers, delegate (PlayerInfo x, PlayerInfo y) { return x.highscore.CompareTo(y.highscore); });

        for(int i = 0; i < allPlayers.Length; i++)
        {
            Debug.Log("Username: "+allPlayers<em>.username+", ID: "+ allPlayers_.id+", Score: "+ allPlayers*.highscore);*_</em>

}

}

* // Update is called once per frame*
* void Update () {*

* }*
}

The result:
[79514-result.png|79514]
The index 0 of the array is the worst player, and the index array.lenght is the best player. If you want the 0 to be the best, all you got to do is:
Array.Reverse(members);

@Mukabr Thanks for the reply. Even though the code works perfectly, i am not very well versed in c# coding and i can’t connect this script with other JavaScript codes i made. So if you or anyone else can convert the code above in JS I’d be very appreciative. Thanks again and sorry for the trouble.