Home > DeveloperSection > Forums > Loop through json result and sort in numeric order in java script
ben reitman
ben reitman

Total Post:96

Posted on    April-04-2013 1:52 AM

 JavaScript JavaScript 

 2 Reply(s)
 1095  View(s)
Rate this:
Hi All!

This is my json:

{"event": { 
"items": [
            {"position": "2", "name": "John Doe 1"},
            {"position" : "1", "name": "John Doe 2"},
            {"position": "3", "name": "John Does 3"}
This is how I loop through results after reading the json result:

$.each(data.event.items, function(val) {
Right now the order is: John Doe 1, John Doe 2, John Doe 3. I want to loop them and display them in order of the position that is has been given. So the 

correct order would be John Doe 2, John Doe 1, John Doe 3.

How can I achieve that?
Thanks in advance!


Total Post:604

Posted on    April-04-2013 7:11 AM

Hi Ben!

you can try this way

sort your items before building the display 

data.event.items.sort(function(a,b) {
   return a.position-b.position;        
Demonstration (click "Run with JS")

Please note that there is no JSON in your problem, data is a plain JavaScript object.

I hope it resolve your problem

Vijay Shukla

Total Post:100

Posted on    April-04-2013 7:24 AM

Hi Ben!

You will need to sort the items first:

data.event.items.sort(function(item_a, item_b) {
    return item_a.position - item_b.position;

Don't want to miss updates? Please click the below button!

Follow MindStick