function byLength( e1 , e2 ) {
// Convert to string and extract the length:
e1 = e1.toString().length;
e2 = e2.toString().length;
return e1>e2 ? 1 : ( e1<e2 ? -1 : 0 );
}
var arr = ["I","learn","the","JavaScript","LANGUAGE","intelligently",76];
arr = arr.sort(byLength); // Custom sort function name as argument
alert( arr.join("\n") ); // Click to run ->
Note: since sort() doesn't modify the original array, we assign its result back in the arr variable.
Tip: we use the join() method, with a new line character as argument, to display one element per line, and the String length property to count the number of characters in each element.
return e1 < e2 ? 1 : ( e1 > e2 ? -1 : 0 ); // Changes highlighted