【问题标题】:how to sort an array of objects based on any one its atributes [duplicate]如何根据其属性对对象数组进行排序[重复]
【发布时间】:2018-11-14 20:53:28
【问题描述】:

我有一个如下的对象数组。

options: [
          {value: 1, label: "test1"},
          {value: 2, label: "test12"},
          {value: 0, label: "test123"}
         ]

我想根据对象的value 属性对该数组进行排序。请让我知道我可以用 Javascript 实现它。

【问题讨论】:

  • 也许我的回答here 会有所帮助。如果您需要更多帮助,请告诉我(不要忘记以 @... 开头)

标签: javascript arrays sorting object


【解决方案1】:

你可以sort

let options = [{
    value: 1,
    label: "test1"
  },
  {
    value: 2,
    label: "test12"
  },
  {
    value: 0,
    label: "test123"
  }
]

options.sort((a, b) => a.value - b.value);

console.log(options);

文档:sort()

【讨论】:

    【解决方案2】:

    你可以像这样使用排序:

    data.sort((a, b) => a.value - b.value);
    

    演示:

    let data =  [
        {value: 1, label: "test1"},
        {value: 2, label: "test12"},
        {value: 0, label: "test123"}
    ];
    
    data.sort((a, b) => a.value - b.value);
    
    console.log(data);

    【讨论】:

    • data.sort((direction => (a, b) => (a.value - b.value)*direction)(-1)); 用于降序,data.sort((direction => (a, b) => (a.value - b.value)*direction)(1)); 用于升序。我通常参考this answer 来编写排序函数。
    猜你喜欢
    • 2021-07-14
    • 2012-10-22
    • 2023-03-15
    • 2017-07-18
    • 2017-04-06
    • 1970-01-01
    • 2020-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多