Quote:
Originally Posted by JonBMN
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' ) );