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.

Matt
  • 74,352
  • 26
  • 153
  • 180
greW
  • 1,248
  • 3
  • 24
  • 49
  • 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)? – T.J. Crowder Jul 14 '14 at 12:51
  • `arr.sort(function (a, b) { return a.order - b.order; })` - that was hard. – deceze Jul 14 '14 at 12:52

3 Answers3

13

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});
dersvenhesse
  • 6,276
  • 2
  • 32
  • 53
  • 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 06 '18 at 11:20
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 });
Coupey
  • 71
  • 5
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

Chris Lam
  • 3,526
  • 13
  • 10