0

I have the following JSON object in javascript:

var stuff = [{
"id": "20",
"serial": "0/0/19:46,0/0/149:63"
}, {
"id": "8",
"serial": "0/0/151:215,0/0/151:233"
}, {
"id": "54",
"serial": "0/0/151:26,0/0/151:37"
}, {
"id": "22",
"serial": "0/0/155:29,0/0/155:36"
}, {
"id": "4",
"serial": "0/0/151:48,0/0/151:152"
}];

I would like to know how to sort the object by the "serial" field, leaving it like this (taking into account the value of the integers in the serial string):

var stuff = [{
"id": "20",
"serial": "0/0/19:46,0/0/149:63"
}, {
"id": "54",
"serial": "0/0/151:26,0/0/151:37"
}, {
"id": "4",
"serial": "0/0/151:48,0/0/151:152"
}, {
"id": "8",
"serial": "0/0/151:215,0/0/151:233"
}, {
"id": "22",
"serial": "0/0/155:29,0/0/155:36"
}];

Thanks in advance.

Samin
  • 610
  • 3
  • 11
  • 22
  • Perhaps search first? http://stackoverflow.com/search?q=%5Bjavascript%5D+sort+JSON – mplungjan Aug 06 '12 at 21:12
  • exact duplicate of [Sorting objects in an array by a field value in JavaScript](http://stackoverflow.com/questions/1129216/sorting-objects-in-an-array-by-a-field-value-in-javascript) – Bergi Aug 06 '12 at 21:15
  • Perhaps I didn't give the best example. I've searched for the solution, but what I was asking is to take into account the integers in the serial field so 0/0/19:46 would come before 0/0/151:26... So it's not a duplicate question mates. – Samin Aug 07 '12 at 00:49

2 Answers2

1

You have an array of objects, which you want to sort by one of their properties. You could very easily do it like this:

stuff.sort(function(a,b) {return a.serial == b.serial ? 0 : a.serial < b.serial ? -1 : 1;});

Alternatively, you could have a more general function:

function sort(input,prop) {
    input.sort(function(a,b) {return a[prop] == b[prop] ? 0 : a[prop] < b[prop] ? -1 : 1;});
}
// call with:
sort(stuff,'serial');
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1

This will do it for you:

var normalizer = /[:\/]/g;

function serialCompare(a, b) {
    var alist = a.serial.replace(normalizer, ',').split(','),
       blist = b.serial.replace(normalizer, ',').split(','),
       i = 0, l = alist.length;
    while (alist[i] === blist[i] && i < l) {
        i += 1;
    };
    return (parseInt(alist[i], 10) - parseInt(blist[i], 10));
}

sortedstuff = stuff.sort(serialCompare);
// returns array sorted as you asked

See it in a fiddle.

If you are going to be sorting often, or the list is very long, you should consider creating a "normalized" version of the serial value that gets stored in the object. It could be the array as calculated inside the serialCompare function, or it could be the text number parts padded to the same lengths with leading zeroes.

ErikE
  • 48,881
  • 23
  • 151
  • 196