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
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
Share Improve this question asked Nov 14, 2012 at 15:18 skywindskywind 9647 gold badges24 silver badges45 bronze badges 1- What you have wrote is not actually valid JSON. JSON keys cannot start with a number. stackoverflow.com/questions/8758715/using-number-as-index-json – Forbesmyester Commented Apr 8, 2013 at 12:45
2 Answers
Reset to default 12Consider 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.
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.