我有一个对象数组,如下所示
[
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
];
答案 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