如何在Javascript中基于第一个数组对二维数组进行排序

时间:2016-09-30 22:18:55

标签: javascript arrays sorting

所以,我有这个数组:

distances = [[Obj1, Obj2, Obj3, Obj4], [15,221,9,2]];

我想基于第二个数组对二维数组进行排序,所以它应该如下所示:

distances = [[Obj4, Obj3, Obj1, Obj2], [2, 9, 15, 221]];

我知道我可以使用这种方法:How to sort 2 dimensional array by column value?,但我似乎无法调整代码。

4 个答案:

答案 0 :(得分:4)

首先,一个相当低效的解决方案是转置您的数组以匹配您在问题中链接的解决方案的布局。

var temp = [];
for(var i in distances[0])
  temp[i] = ([distances[0][i], distances[1][i]]);

然后进行排序并将其转换回之前的形式:

distances = [[], []];
for (var i in temp) {
  distances[0][i] = temp[i][0];
  distances[1][i] = temp[i][1];
}

答案 1 :(得分:3)

您可以使用临时数组作为排序顺序,并将其应用于distances的两个数组。



var distances = [['Obj1', 'Obj2', 'Obj3', 'Obj4'], [15, 221, 9, 2]],
    order = distances[0].map(function (_, i) { return i; });

order.sort(function (a, b) {
    return distances[1][a] - distances[1][b];
});

distances[0] = order.map(function (i) { return distances[0][i]; });
distances[1] = order.map(function (i) { return distances[1][i]; });

console.log(distances);




答案 2 :(得分:3)

var sorted = distances[1].map(function (v, i) { 
   return {v:v,i:i,o:distances[0][i]} }).
      sort(function (a,b) { return a.v - b.v});
distances[0] = sorted.map(function (x) { return x.o });
distances[1] = sorted.map(function (x) { return x.v });

答案 3 :(得分:2)



var distances = [["Obj1", "Obj2", "Obj3", "Obj4"], [15,221,9,2]];

var NewDistances = [];
for (var i = 0; i < distances[0].length; i++)
  NewDistances[i] = {
    Obj: distances[0][i],
    Key: distances[1][i]
  };
NewDistances.sort(function(O1, O2) {
  return O1.Key < O2.Key ? -1 : (O1.Key > O2.Key ? 1 : 0);
});
var Result = [[],[]];
for (var i = 0; i < NewDistances.length; i++) {
  Result[0][i] = NewDistances[i].Obj;
  Result[1][i] = NewDistances[i].Key;
}

console.log(Result);
&#13;
&#13;
&#13;