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
The sort(), sorted(), and dumps() functions have been used here to sort the JSON object in ascending and descending order.
The JSON. parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.
When using the JSON.parse () on a JSON derived from an array, the method will return a JavaScript array, instead of a JavaScript object. Example. The JSON returned from the server is an array: var xmlhttp = new XMLHttpRequest ();
The constructor of a JSONObject can be used to convert an external form JSON text into an internal form whose values can be retrieved with the get () and opt () methods or to convert values into a JSON text using the put () and toString () methods. In the below example, we can sort the values of a JSONObject in the descending order.
Example - Parsing JSON. Imagine we received this text from a web server: Use the JavaScript function JSON.parse() to convert text into a JavaScript object: var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}'); Make sure the text is written in JSON format, or else you will get a syntax error.
The sort method also checks by letter ordering. We can take the same above example and represent it in if-else a statement. This method reverses the array.As sort () method sorts array items to ascending order calling reverse () method on sort () like sort ().reverse () does the opposite of that it orders items in descending order.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With