4

I have the following JSON:

{
    title: 'title',
    ...,
    order: 0
}, {
    ...,
    order: 9
}, {
    ...,
    order: 2
}

... the JSON includes many fields, how can I sort them based on the order field?

I was looking for something build into nodejs but I couldn't find anything that might be useful for that case.

2
  • 2
    That's not JSON. It looks like it's the inside of an array initializer. Are you working with text (e.g., JSON), or objects (e.g., the result of evaluating an array initializer)? Jul 14, 2014 at 12:51
  • arr.sort(function (a, b) { return a.order - b.order; }) - that was hard.
    – deceze
    Jul 14, 2014 at 12:52

3 Answers 3

14

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});
1
  • 1
    this worked fine, but i needed to sort it in desc order, so i changed inner function to return: return b.order - a.order;
    – Saeedses
    Apr 6, 2018 at 11:20
1

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

1

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 });

Not the answer you're looking for? Browse other questions tagged or ask your own question.