In a javaScript book I am reading, it sites a handy function which helps the sort method output the values in the correct order (in the case of numbers).
var values = [0,1,5,10,15];
values.sort();
console.log(values); //outputs 0,1,10,15,5
function compare (value1, value2){
if (value1 < value2){
return -1;
} else if (value1 > value2){
return 1;
} else {
return 0;
}
var values = [0,1,5,10,15];
values.sort(compare);
console.log(values); //outputs 0,1,5,10,15
I know what's ultimately happening but I am bit perplexed as how the 'compare' function is doing it! Mostly because I am not sure how the return values of the 'compare' function are effecting the array! Thanks friends!