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);
    });
}
gotnull
  • 26,454
  • 22
  • 137
  • 203

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
  • 741,623
  • 53
  • 500
  • 612
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
  • 42,889
  • 6
  • 74
  • 90