localStorage sort order by value

☆樱花仙子☆ 提交于 2019-12-24 03:50:37

问题


I've put some data in localStorage, and I want to retrieve to key names in an array, ordered by the value:

France : 0
Italy: 1
England: 2
Germany: 3
.. etc.

function getCountries() {
    "use strict";
    var returnArray = [];
    for (var i = 0; i < localStorage.length; i++) {
        returnArray.push(localStorage.key(i));
    }

    return returnArray;
}

Right now the order of the key-names in the array seems to be quite random - how to order the array by the values?


回答1:


If you want to sort in multiple places you can create a prototype.

Array.prototype.sortOnValue = function(key){
    this.sort(function(a, b){
        if(a[key] < b[key]){
            return -1;
        }else if(a[key] > b[key]){
            return 1;
        }
        return 0;
    });
}

Created a fiddle of how to use it.




回答2:


var countries = Object
    .keys(localStorage)
    .sort(function(a, b) {
      return localStorage[a] - localStorage[b];
    }) 


来源:https://stackoverflow.com/questions/38807946/localstorage-sort-order-by-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!