nick
nick

Reputation: 3239

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.

Upvotes: 1

Views: 140

Answers (4)

Keith
Keith

Reputation: 24181

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

Upvotes: 3

Dakusan
Dakusan

Reputation: 6691

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

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386570

You could use a temporary array for the sort order and apply this to the two arrays of 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);

Upvotes: 3

jan
jan

Reputation: 81

First, a rather unefficient solution would be to transpose your array to match the layout of the solution you linked in your question.

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

Then do the sorting and transform it back to its previous form:

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

Upvotes: 4

Related Questions