排序多维数组

时间:2012-07-24 12:00:54

标签: javascript sorting

我有以下JavaScript数组,

var myArr= [{
    "key" : "Consumer Discretionary",
    "values" :[ 
               [1146369600000, 26.425199957521],
               [1138683600000, 27.38478809681],
               [1141102800000, 27.371377218208], 
               [1143781200000, 26.309915460827] 
              ]}, 
    {
     "key" : "Consumer Staples",
     "values" :[
                [1159588800000, 7.2800122043237], 
                [1141102800000, 7.1187787503354], 
                [1167541200000, 8.351887016482], 
                [1146369600000, 8.4156698763993]
              ]}
     ];

我如何按升序排列“关键”消费者自由裁量权和消费者订书钉的“价值”,以便它看起来像

非必需消费品: -

[1138683600000, 27.38478809681] 
[1141102800000, 27.371377218208] 
[1143781200000, 26.309915460827]
[1146369600000, 26.425199957521]

对此有何帮助? 提前致谢

1 个答案:

答案 0 :(得分:2)

尝试以下方法:

function valuePredicate(a,b){
    return a[0]!==b[0] ? a[0]-b[0] : a[1]-b[1];
}

for(var i=0; i < myArr.length;++i){
    myArr[i].values.sort(valuePredicate);
}

Live demo