1

I am trying to sort an array. For instance, given array a (below), I would like to return array b.

I know I can do a.sort(), however, I don't want to sort on the actual array element, but on a property (s for this example) of the array element. How can this be accomplished?

Thank you

var a=[
  {s:"ced",o:{obj:1}},
  {s:"cde",o:{obj:2}},
  {s:"ade",o:{obj:3}},
  {s:"bde",o:{obj:4}}
]

var b=[
  {s:"ade",o:{obj:3}},
  {s:"bde",o:{obj:4}},
  {s:"cde",o:{obj:2}},
  {s:"ced",o:{obj:1}}
]
Paul S.
  • 64,864
  • 9
  • 122
  • 138
user1032531
  • 24,767
  • 68
  • 217
  • 387
  • Duplicates: [here](http://stackoverflow.com/questions/8900732/javascript-sort-objects-in-an-array-alphabetically-on-one-property-of-the-arra) and [here](http://stackoverflow.com/questions/8966247/sort-objects-by-a-property-values) – lbstr Nov 13 '12 at 21:56

3 Answers3

7

Array.prototype.sort accepts an optional parameter: a callback telling it how to sort.

a.sort(function(x,y) {
    // do something here
    // return -1 if x < y
    // return  1 if x > y
    // otherwise, return 0
});

So, in your case, it would be:

a.sort(function(x,y) {return x.s == y.s ? 0 : (x.s < y.s ? -1 : 1);});
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • Thanks Kolink. What is x and y? For instance, is x the current item and y the highest or lowest? – user1032531 Nov 13 '12 at 19:46
  • They are two items from the array, picked by the `sort` function to try and work out what order they go in. for example, if the input array is `[2,3,1]` then it might ask "what order do 2 and 3 go in?"... "what about 2 and 1?"... before getting to "okay, I got it, it's `[1,2,3]`." The point is you don't need to know *which* items they are, all you need to know is that they are two items and you are being asked how to compare them. – Niet the Dark Absol Nov 13 '12 at 19:50
1

The sort method accepts a compareFunction parameter, where you can define how to calculate sort order.
As you want to compare strings this function should use localeCompare as suggested here.
One way to create a sorting function which can be quickly adjusted is to generate it via another function. This means you can create sort functions automatically for any property of an object.
Put the two to together and you get..

function genSortFn(prop){
    return function(a,b){ return a[prop].localeCompare( b[prop] ); };
}
a.sort( genSortFn('s') );
b.sort( genSortFn('s') );
Community
  • 1
  • 1
Paul S.
  • 64,864
  • 9
  • 122
  • 138
1
a.sort(function(a, b){
    if(a.s < b.s){
        return -1;
    }
    if(a.s > b.s){
        return 1;
    }
    return 0;
});

http://jsfiddle.net/lbstr/nCKpG/

lbstr
  • 2,822
  • 18
  • 29