View Single Post
Old 02-28-2013, 04:37 PM   PM User | #7
Logic Ali
Regular Coder

 
Logic Ali's Avatar
 
Join Date: Sep 2010
Location: London
Posts: 960
Thanks: 0
Thanked 198 Times in 193 Posts
Logic Ali will become famous soon enoughLogic Ali will become famous soon enough
Quote:
Originally Posted by JonBMN View Post
I understand using the callback function in .sort but I get back .sort() is not a function.
Then you're not calling it on an array. You'll have to show your code.

I think you want to be able to specify the sorting key, in which case you can write a function to do it. You cant pass parameters to the callback function, that is what sort() does.
Code:
objArray = [ {q:2, r:6}, {q:1, r:2}, {q:3, r:-5}, {q:9.7, r:-1}, {q:-4, r:0} ];

Array.prototype.sortOnKey = function( key )
{
  this.sort( function(a, b){ return a[ key ] - b[ key ]; } );
  
  return this;
}

console.log( objArray.sortOnKey( 'q' ) );

console.log( objArray.sortOnKey( 'r' ) );
Logic Ali is offline   Reply With Quote