如何在JavaScript中按属性值对对象数组进行排序

本文介绍如何使用JavaScript的Array.sort()方法对对象数组进行排序,包括按颜色名称等属性的字母顺序排序,以及处理颜色相同情况下按大小排序的复杂情况。

Say you have an array of objects like this:

假设您有一系列这样的对象:

const list = [
  { color : 'white' , size : 'XXL' },
  { color : 'red' , size : 'XL' },
  { color : 'black' , size : 'M' }
]

You want to render this list, but first you want to order it by the value of one of the properties. For example you want to order it by the color name, in alphabetical order: black, red, white.

您要呈现此列表,但首先要按其中一个属性的值对其进行排序。 例如,您要按颜色名称(按字母顺序)进行排序:黑色,红色,白色。

You can use the sort() method of Array, which takes a callback function, which takes as parameters 2 objects contained in the array (which we call a and b):

您可以使用Arraysort()方法,该方法带有一个回调函数,该函数将数组中包含的2个对象(我们称为ab )作为参数:

list . sort (( a , b ) => ( a . color > b . color ) ? 1 : - 1 )

When we return 1, the function communicates to sort() that the object b takes precedence in sorting over the object a. Returning -1 would do the opposite.

当我们返回1,到功能连通sort()对象b优先于在对象排序a 。 返回-1则相反。

The callback function could calculate other properties too, to handle the case where the color is the same, and order by a secondary property as well:

回调函数还可以计算其他属性,以处理颜色相同的情况,并按次要属性进行排序:

list . sort (( a , b ) => ( a . color > b . color ) ? 1 : ( a . color === b . color ) ? (( a . size > b . size ) ? 1 : - 1 ) : - 1 )

翻译自: https://flaviocopes.com/how-to-sort-array-of-objects-by-property-javascript/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值