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):
您可以使用Array的sort()方法,该方法带有一个回调函数,该函数将数组中包含的2个对象(我们称为a和b )作为参数:
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/
本文介绍如何使用JavaScript的Array.sort()方法对对象数组进行排序,包括按颜色名称等属性的字母顺序排序,以及处理颜色相同情况下按大小排序的复杂情况。
681

被折叠的 条评论
为什么被折叠?



