Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This question already has an answer here:

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

share|improve this question

marked as duplicate by Bergi Nov 7 '14 at 2:11

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1 Answer 1

up vote 2 down vote accepted

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

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.