solaire
solaire

Reputation: 505

Issue with shared sorting function in javascript

I have a list of users with properties and I want to output a best list according to each propertly. When I comment out "nrGames": sorter(allUsersWithStats, "nrGames") it correctly sorts according to elo, but if I don't, both are sorted according to nrGames. I guess somehow I need to use a new instance of allUsersWithStats to prevent it but I am not exactly sure.

async function getRankedUserList() {
    allUsersWithStats = await getAllUsersWithStats();
    topList = {
        "elo": sorter(allUsersWithStats, "elo"),
        "nrGames": sorter(allUsersWithStats, "nrGames"),
    }
    return topList;
}

function sorter(allUsersWithStats, propertyName) {
    return allUsersWithStats.sort(function (a, b) {
        return b[propertyName] - a[propertyName];
    });
} 

The allUsersWithStats Array looks like this:

[
  {
    name: 'Bob',
    elo: 962,
    nrGames: 2,
  },
  {
    name: 'John',
    elo: 979,
    nrGames: 3,
  }
]

Upvotes: 0

Views: 56

Answers (1)

Ehsan
Ehsan

Reputation: 1113

Javascript sort function mutates the array.

So you should copy the array first and then send it to your function

async function getRankedUserList() {
    allUsersWithStats = await getAllUsersWithStats();
    topList = {
        "elo": sorter([...allUsersWithStats], "elo"),
        "nrGames": sorter([...allUsersWithStats], "nrGames"),
    }
    return topList;
}

Or

function sorter(allUsersWithStats, propertyName) {
    return [...allUsersWithStats].sort(function (a, b) {
        return b[propertyName] - a[propertyName];
    });
}

Upvotes: 2

Related Questions