skywind
skywind

Reputation: 962

How to sort (reverse) object of jsonparse?

I have object {"5":"5","4":"4","3":"3","2":"2","1":"1","-1":"P1",-2":"P2"} And use this function to parse elements:

function floormake(inobj) {
    var levels = '';
    var obj = JSON.parse(inobj);
    levels += '<ul>';
    Object.keys(obj).sort(-1).forEach(function (key) {
        levels += '<li>' + obj[key] + '</li>';
    });
    levels += '</ul>';
    return levels;
}

But result alway sorting by number: -1, -2, 1, 2 etc. BUT i need reverse sorting: 5, 4, 3, 2, 1, sort(-1) - doesn't work

Upvotes: 6

Views: 28194

Answers (2)

Ian
Ian

Reputation: 50923

The Array.sort method does not accept an integer as the only optional parameter. It accepts a reference to a function that either returns -1, 0, or 1, and the details can be found here: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/sort

Here's an example of how to sort based on number:

http://jsfiddle.net/3HFN5/1/

var a = ["5", "9", "1", "399", "23", "21"];

function sorter(b, c) {
    return (+b < +c ? 1 : -1);
}

alert(a.sort(sorter));

Or something simpler/better:

http://jsfiddle.net/3HFN5/2/

var a = ["5", "9", "1", "399", "23", "21"];

function sorter(b, c) {
    return c - b;
}

alert(a.sort(sorter));

And incorporating this with your actual example:

http://jsfiddle.net/3HFN5/3/

var a = {"2":"2","4":"4","-2":"P2","3":"3","300":"4","1":"1","5":"5","-1":"P1"};

function sorter(b, c) {
    return c - b;
}

alert(Object.keys(a).sort(sorter));

I mixed the items in the object around and added one to prove it's sorting accurately/completely.

Upvotes: 5

Joel Etherton
Joel Etherton

Reputation: 37543

Consider using .reverse() instead.

Object.keys(obj).sort().reverse().forEach( ....

Reverse documentation

Edit Note: As mentioned by @Shmiddty, the reverse() method does not actually sort. The array will need to be sorted then reversed.

Upvotes: 12

Related Questions