Making a simple leader board in memory Im trying to think of the most efficient way to structure an in memory leader board with the ability to read a specific rank quickly. Im talking about very micro optimisations as either way it will still be fast.

class Leaderboard
{
    constructor()
    {
        this.leaderboard = [];
    }

    insert(name, score)
    {
        const player = new Player(name, score, new Date());
        this.leaderboard.push(player);
        this.leaderboard.sort((a, b) =&gt; a.score - b.score);
    }

    getRank(rank)
    {
        if (isNaN(rank) || rank &lt; 1 || rank &gt; this.leaderboard.length) return null;
        return this.leaderboard[rank - 1];
    }
}

class Player
{
    constructor(name, score, date)
    {
        this.name = name;
        this.score = score;
        this.date = date;
    }
}

const leaderboard = new Leaderboard();

leaderboard.insert('john', 36);
leaderboard.insert('pete', 23);
leaderboard.insert('dave', 56);

console.log(leaderboard.getRank(2));


This is what I have come up with, any feedback is great and any small optimisations or completely different and better ways are welcome, thankyou
Your implementation depends on this.leaderboard.sort((a, b) =&gt; a.score - b.score);. Each and every time you insert, you sort again.

Depending on your access pattern, you could defer the sorting from adding to reading.

You could operate with a dictionary keeping the scores unorderd which makes inserting fast. And sort the entries only in case if you read them.

For the sake of the example I used plain numbers

let leaderboard = {
}

const addScore = (board, score) =&gt; {
  if(!board[score]) board[score] = []
  board[score].push(score)
  return board;
}

const getcurrentRanks = (board) =&gt; {
    const scoreranks = Object.keys(board).sort((a,b)=&gt;b-a)
    return scoreranks.reduce((o,n )=&gt;{
        return o.concat(board[n]);
    }, []);
}


But this has the downside of converging to your first implementation the more you read; e.g. for each time you insert a value you want to get all the ranks.

Otherwise I would encourage you to look into priority queues.