按字符串属性值对对象数组排序

有 JavaScript 对象数组:

var objs = [ 
    { first_nom: 'Lazslo', last_nom: 'Jamf'     },
    { first_nom: 'Pig',    last_nom: 'Bodine'   },
    { first_nom: 'Pirate', last_nom: 'Prentice' }];

如何根据 JavaScript 中last_nom的值对它们进行排序?
我知道 sort (a,b) ,但它似乎只对字符串和数字起作用。 是否需要向对象中添加 toString()?

在 es6 / es2015或更高版本中,可以这样做:
objs.sort((a, b) => a.last_nom.localeCompare(b.last_nom));

编写自己的比较函数非常简单:

function compare( a, b ) {
  if ( a.last_nom < b.last_nom ){
    return -1;
  }
  if ( a.last_nom > b.last_nom ){
    return 1;
  }
  return 0;}
objs.sort( compare );
或 inline (c / o Marco Demaio) :
objs.sort((a,b) => (a.last_nom > b.last_nom) ? 1 : ((b.last_nom > a.last_nom) ? -1 : 0));

你也可以创建一个动态排序函数,根据你传递的值对对象进行排序:

function dynamicSort(property) {
    var sortOrder = 1;
    if(property[0] === "-") {
        sortOrder = -1;
        property = property.substr(1);
    }
    return function (a,b) {
        /* next line works with strings and numbers, 
         * and you may want to customize it to your needs
         */
        var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
        return result * sortOrder;
    }}

所以有类似这样的对象数组:

var People = [
    {Name: "Name", Surname: "Surname"},
    {Name:"AAA", Surname:"ZZZ"},
    {Name: "Name", Surname: "AAA"}];

会管用的
People.sort(dynamicSort("Name"));People.sort(dynamicSort("Surname"));People.sort(dynamicSort("-Surname"));

不理解为什么大家把事情弄得这么复杂:

objs.sort(function(a, b){
  return a.last_nom > b.last_nom;});

还不行?换这个:

objs.sort(function(a, b){
  return a.last_nom == b.last_nom ? 0 : +(a.last_nom > b.last_nom) || -1;});

将操作符交换为按反向字母顺序排序。