francoleung francoleung - 2 months ago 9
Javascript Question

How to sort Json by id 's values newest to oldest ,Thanks

How to sort JSON by id's values newest to oldest?

My HTML



<script>
$(document).ready(function() {
var url = "json.php";
$.getJSON(url, function(result) {
console.log(result);
$.each(result, function(i, field) {
var id = field.id;
var name = field.name;
var category = field.category;
$("#show_data").append("<li class='item'>"+"<div>"+ id +"</div>"+ "<p>"+ name +"</p>" +"<p>" + category +"</p></li>");
});
});
});</script><body><ul><div id="show_data"></div><ul>


MY Json.php file

[{
"id": "1",
"name": "Mary",
"category": "eng"
}, {
"id": "2",
"name": "Peter",
"category": "super"
}, {
"id": "3",
"name": "Ben",
"category": "math"
}]


the result is this:

id:1
name:Mary
category:eng

id:2
name:Peter
category:super

id:3
name:Ben
category:math

but i want to show it

id:3
name:Ben
category:math

id:2
name:Peter
category:super
id:1

name:Mary
category:eng

id:3 --> id-->2 id:--1

Can anyone help? Thank you so much, I love you!! thanks!! thx thx thxthx

Answer

Sort the result in descending order of id before manipulating the dom

var sortedResult = result.sort(function(a, b) {
  return b.id - a.id
})
$.each(sortedResult, function(i, field) {
  // Rest of the code
});