The array of javascript objects is sorted by the value of the object object key


There is an array of js objects var ary=[{id:1,name:“b”},{id:2,name:“b”}] the requirement is to sort by name or id values, here is a fancy function

Function definition:

function keysrt(key,desc) {
  return function(a,b){
    return desc ? ~~(a[key] < b[key]) : ~~(a[key] > b[key]);
  }
}

Use:

var ary=[{id:1,name:"b"},{id:2,name:"b"}];
ary.sort(keysrt('name',true));
ary.sort(keysrt('name',false));
ary.sort(keysrt('id',false));

The above is the entire content of this article, there is a need for friends to study it, ha ha.