The Simon The Simon - 1 year ago 175
Javascript Question

localStorage sort order by value

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++) {

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download