Reputation: 962
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
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:
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:
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:
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
Reputation: 37543
Consider using .reverse()
instead.
Object.keys(obj).sort().reverse().forEach( ....
Edit Note: As mentioned by @Shmiddty, the reverse() method does not actually sort. The array will need to be sorted then reversed.
Upvotes: 12