【问题标题】:How to sort array by property in Javascript [duplicate]如何在Javascript中按属性对数组进行排序[重复]
【发布时间】:2020-10-06 22:43:22
【问题描述】:

我有一个数组如下:

const list = [
  { id: 1, name: 'Product 1', color: 'white'},
  { id: 2, name: 'Product 2', color: 'black'},
  { id: 3, name: 'Product 3', color: 'red'},
  { id: 4, name: 'Product 4', color: 'white'},
  { id: 5, name: 'Product 5', color: 'black'},
]

我想根据预定义的颜色顺序对数组进行排序:红色 -> 白色 -> 黑色并输出:

const list = [
  { id: 3, name: 'Product 3', color: 'red'},
  { id: 1, name: 'Product 1', color: 'white'},
  { id: 4, name: 'Product 4', color: 'white'},
  { id: 5, name: 'Product 5', color: 'black'},
  { id: 2, name: 'Product 2', color: 'black'}
]

【问题讨论】:

标签: javascript


【解决方案1】:
let colorPriority = ['red', 'white', 'black'];
list = list.sort((obj1, obj2) => colorPriority.indexOf(obj1.color) - colorPriority.indexOf(obj2.color));

这段代码应该适合你。

【讨论】:

  • 如果 OP 想要修改它,list 也应该从 const 更改为 let。否则,您将需要一个新变量。
  • 好收获。我会更新答案。谢谢
猜你喜欢
  • 2014-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-06
  • 2017-05-31
  • 1970-01-01
  • 2012-10-06
相关资源
最近更新 更多