【发布时间】:2016-07-13 10:13:20
【问题描述】:
我有一个对象数组,如下所示,需要以这样的方式对其进行排序,即先有 c 的项目,然后是 y ,然后是 s。在这方面,例如在c中,它应该按计数器排序,即c-counter 1,c-counter 2。
var data = [ { age:7, counter: 1, code: 'c'},
{ age:5, counter: 2, code: 'c'},
{ age:4, counter: 3, code: 'c'},
{ age:19, counter: 2, code: 'y'},
{ age:22, counter: 1, code: 'y'},
{ age:57, counter: 1, code: 's'},
{ age:80, counter: 2, code: 's'}
]
在查看 SO 时,我能够按 c、y、s 排序,如下所示,但无法对里面的 counter 进行另一种排序。我该怎么做。
var order =[c,y,s];
data.sort(function(a,b){
return order.indexOf(a.code) < order.indexOf(b.code) ? -1:1;
})
【问题讨论】:
标签: javascript arrays sorting