排序字符串数组,其中的元素如" Name:Score"

时间:2017-08-11 14:29:14

标签: javascript jquery sorting web

我有一个存储在LocalStorage中的字符串数组。这个数组的每个元素都是一个字符串" Name:Score"。我需要按分数对此数组进行排序以构建顶部。我怎样才能更有效地做到这一点? 也许我应该将玩家的统计数据存储起来,而不是像数组那样更容易排序。

到目前为止我的代码:

function saveResult() {
    let userName = $("#input-user-name").val();
    let userStat = userName + ":" + playerScore;
    results = localStorage.getItem("gameResults");
    if (results === null) {
        localStorage.setItem("gameResults", JSON.stringify([userStat]));
    } else {
        results = JSON.parse(localStorage.getItem("gameResults"));
        results.push(userStat); //sort 
        localStorage.setItem("gameResults", JSON.stringify(results));
    }
    updateStatTable();
}

1 个答案:

答案 0 :(得分:1)

使用sort()非常简单:



var arr = ['John:32', 'Jack:45', 'Mary:25']

arr.sort((a, b) => a.split(':')[1] < b.split(':')[1])

console.log(arr)
&#13;
&#13;
&#13;