user1032531
user1032531

Reputation: 26281

Sort a javascript array of objects by object property

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}}
]

Upvotes: 1

Views: 337

Answers (3)

Paul S.
Paul S.

Reputation: 66334

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') );

Upvotes: 1

lbstr
lbstr

Reputation: 2832

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/

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324640

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);});

Upvotes: 7

Related Questions