1

I have an array structured like this, for any existing index i:

myArray[i] = [anIndex, aValue]

For example, its contents can be as follows:

myArray[0] = [2, 35]
myArray[1] = [3, 57]
myArray[2] = [5, 12]
myArray[3] = [6, 42]

I would like to sort this array in ascending order while keeping the same structure, and using aValue as the sorting parameter. In the case of the above example, I would get this result, for each index of the resulting sorted array:

  • index 0: [5, 12]
  • index 1: [2, 35]
  • index 2: [6, 42]
  • index 2: [3, 57]

I don't really understand how to achieve this using array.sort() - or if it's even possible. Thanks

user1070447
  • 147
  • 10

1 Answers1

2

Like this, using Array.prototype.sort() with a compareFunction:

var myArray = [];
myArray[0] = [2, 35];
myArray[1] = [3, 57];
myArray[2] = [5, 12];
myArray[3] = [6, 42];

myArray = myArray.sort(function(x, y) {
  return x[1] - y[1];
});

console.log(myArray);
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156