Skip to content Skip to sidebar Skip to footer

How To Sort JSON By A Single Integer Field?

I have the following JSON: { title: 'title', ..., order: 0 }, { ..., order: 9 }, { ..., order: 2 } ... the JSON includes many fields, how can I sort t

Solution 1:

At first, your need valid JSON, like that:

var unsorted = {
    "items": [
        {
            "title": "Book",
            "order": 0
        },
        {
            "title": "Movie",
            "order": 9
        },
        {
            "title": "Cheese",
            "order": 2
        }
    ]
};

Afterwards you can easily sort the items and store them in a list.

var sorted = unsorted.items.sort(function(a, b) {return a.order - b.order});

Solution 2:

Demo: http://jsfiddle.net/6eQbp/2/

You can use the Array.sort() method to do the sorting.

Ref: http://www.javascriptkit.com/javatutors/arraysort.shtml


Solution 3:

A quick way would be to use a library like underscore.js - it's got a lot of functions that help you do exactly this kind of manipulation with JSON objects.

I've not tested this, but something along these lines:

_.sortBy(yourJSONdata, function(obj){ return +obj.order });

Post a Comment for "How To Sort JSON By A Single Integer Field?"