0

At the moment I'm using the following to sort TypeCode (string) in a response object.

This seems a little over kill. Is there an easier way to achieve this with one for each loop?

if (response && response.length > 0) {
    var sortedArray = [];
    $.each(response, function (i, dict) {
        sortedArray.push(dict.TypeCode);
    });
    sortedArray.sort();
    $.each(sortedArray, function (i, dict) {
        console.log(dict);
    });
}
fulvio
  • 25,423
  • 20
  • 127
  • 202

2 Answers2

1

Sort the original response array, by providing a comparison function that compares the TypeCode properties of each element.

response.sort(function(a, b) {
    return a.TypeCode - b.TypeCode
});
$.each(response, function(i, dict) {
    console.log(dict.TypeCode);
});
Barmar
  • 669,327
  • 51
  • 454
  • 560
1

I assumed TypeCode was a number. You can pas a compareFunction to sort.

var sortedResponse = response.sort(function (d1, d2) {
    return d1.TypeCode - d2.TypeCode;
});

If TypeCode is a string then:

var sortedResponse = response.sort(function (d1, d2) {
    var type1 = d1.TypeCode, type2 = d2.TypeCode;

    return type1 < type2? -1 : +(type1 > type2);
});
plalx
  • 41,415
  • 5
  • 69
  • 87
  • Apologies, `TypeCode` is a string. – fulvio May 08 '14 at 01:12
  • What if I wanted to order by `TypeCode` desc or asc? – fulvio May 08 '14 at 01:23
  • @gotnull Well you can just inverse the conditions. Basically, if `type1` is smaller than `type2`, we return `-1`, if it's the opposite we return `1` and if both are equal we return `0`. – plalx May 08 '14 at 01:27