nick nick - 2 months ago 6
Javascript Question

How to sort two dimensional array based on first array in Javascript

So, I have this array:

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


I want to sort the two dimensional array based on the second array so it should look like this:

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


I know I can use this method: How to sort 2 dimensional array by column value?, but I can't seem to adapt the code.

Answer

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);

Comments