localStorage sort order by value

2019-07-08 10:32发布

问题:

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];
    })