Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript中共享排序函数的问题_Javascript_Typescript_Sorting - Fatal编程技术网

javascript中共享排序函数的问题

javascript中共享排序函数的问题,javascript,typescript,sorting,Javascript,Typescript,Sorting,我有一个具有属性的用户列表,我想根据每个属性输出一个最佳列表。当我注释掉“nrGames”:sorter(allUsersWithStats,“nrGames”)时,它会根据elo正确排序,但如果我不这样做,则两者都会根据nrGames进行排序。我想我需要使用一个新的allUsersWithStats实例来阻止它,但我不太确定 async function getRankedUserList() { allUsersWithStats = await getAllUsersWithSta

我有一个具有属性的用户列表,我想根据每个属性输出一个最佳列表。当我注释掉“nrGames”:sorter(allUsersWithStats,“nrGames”)时,它会根据elo正确排序,但如果我不这样做,则两者都会根据nrGames进行排序。我想我需要使用一个新的
allUsersWithStats
实例来阻止它,但我不太确定

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];
    });
} 
allUsersWithStats
数组如下所示:

[
  {
    name: 'Bob',
    elo: 962,
    nrGames: 2,
  },
  {
    name: 'John',
    elo: 979,
    nrGames: 3,
  }
]
Javascript函数对数组进行变异

因此,您应该首先复制数组,然后将其发送给函数

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

Javascript函数对数组进行变异

因此,您应该首先复制数组,然后将其发送给函数

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