简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM