按字符串属性值对对象数组进行排序 [英] Sort array of objects by string property value

查看:29
本文介绍了按字符串属性值对对象数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组 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' }
];

如何在 JavaScript 中按照 last_nom 的值对它们进行排序?

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

或内联(转自 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))

这篇关于按字符串属性值对对象数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆