如何通过元素值对对象数组进行排序?

时间:2019-12-02 13:04:06

标签: javascript typescript

我有一个对象数组,如下所示

 [
  0: {name: "CMT", priority: 2}
  1: {name: "CDR BILLING", priority: 1}
  2: {name: "POOL DATA", priority: 5}
  3: {name: "FFM", priority: 3}
  4: {name: "SMPP", priority: 6}
  5: {name: "OTC", priority: 4}
 ];

如何对该数组进行排序,以使优先级为1的元素应该在0索引处。我想要实现的是

  [
  0: {name: "CDR BILLING", priority: 1}
  1: {name: "CMT", priority: 2}
  2: {name: "FFM", priority: 3} .....and so on
  ];

2 个答案:

答案 0 :(得分:2)

您可以使用sort方法

let list = [
 {name: "CMT", priority: 2},
 {name: "CDR BILLING", priority: 1},
 {name: "POOL DATA", priority: 5},
 {name: "FFM", priority: 3},
 {name: "SMPP", priority: 6},
 {name: "OTC", priority: 4}
 ];
 
let listCopy = [...list];
listCopy.sort(function (a, b) {
  return a.priority - b.priority;
});

console.log(listCopy);

答案 1 :(得分:-1)

[
   {name: "CMT", priority: 2},
   {name: "CDR BILLING", priority: 1},
   {name: "POOL DATA", priority: 5},
   {name: "FFM", priority: 3},
   {name: "SMPP", priority: 6},
   {name: "OTC", priority: 4}
 ].sort((a,b)=>a.priority-b.priority) //! edited