Search code examples
javascriptvariablesleaderboard

How to display a leaderboard of variables JS


so I made variables with the value 0 and whenever an event is triggered it adds 1 to the variable, I was wondering if theres any way to show a leaderboard of the variables in order (from biggest to smallest), If you know a way please let me know and I appreciate it in advance. :)


Solution

  • You can't really sort variables as they are separate objects. You would need to gather them into a collection and sort that or store your variables in a collection to begin with - a Map object is the most likely candidate for that. Here's an example of what you could do with an array:

        let a = 100;
        let b = 5;
        let c = 75;
        let d = 6;
        let e = 23;
    
        let arr = [];
        arr.push({variable: "a", value:a});
        arr.push({variable: "b", value:b});
        arr.push({variable: "c", value:c});
        arr.push({variable: "d", value:d});
        arr.push({variable: "e", value:e});
    
        arr.sort(function(a, b) {return a.value - b.value});
    
        for (let i = 0; i < arr.length; i++) {
          console.log(arr[i].variable + ": " + arr[i].value);
        }