Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

If I have an array that looks like the following:

var array[0] = [$name, $date, $bTrue]; ... ... ...

How would I sort that array by one of the 1st dimensional array values? Thanx in advance!

share|improve this question

1 Answer

up vote 2 down vote accepted

With a simple sort callback

var arr = [[1,5,2],[1,8,2],[1,2,2]];

console.log( arr );

arr.sort( function( a, b )
{
  // Sort by the 2nd value in each array
  if ( a[1] == b[1] ) return 0;
  return a[1] < b[1] ? -1 : 1;
});

console.log( arr );

the Array.sort() method takes a callback into which two elements are passed. It's a basic bubble sort

  • If a is to be sorted ahead of b, return -1 (or any negative value)
  • If b is to be sorted ahead of a, return 1 (or any positive value)
  • If a and b are equal, return 0;
share|improve this answer
Thanks Peter, I appreciate the quick response. – thepip3r Dec 8 '10 at 12:28

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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