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

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

问题描述:

我有一个JavaScript对象数组:

I have an array of JavaScript objects:

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

如何按 last_nom $ c $的值对它们进行排序c>在JavaScript?

How can I sort them by the value of last_nom in JavaScript?

我知道 sort(a,b),但这似乎只能起作用字符串和数字。我是否需要在对象中添加 toString()方法?

I know about sort(a,b), but that only seems to work on strings and numbers. Do I need to add a toString() method to my objects?

编写自己的比较函数很容易:

It's easy enough to write your own comparison function:

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

或内联(c / o Marco Demaio):

Or inline (c/o Marco Demaio):

objs.sort((a,b) => (a.last_nom > b.last_nom) ? 1 : ((b.last_nom > a.last_nom) ? -1 : 0));