
I was working on porting some enhancement to new version and found some interesting javascript code similar to this:
array.sort(sortorder);
First I didn't get what that parameter ( sortorder) is, then a careful look revealed that it is a function that is written to change the default sort behavior and add some custom sort logic.
function sortorder(a, b){
//Compare a, b with some logic and return a value (-1, 0, 1)
}
//Compare a, b with some logic and return a value (-1, 0, 1)
}
In order to understand this correctly, I researched a bit and found some interesting points with the sort() function of javascript. By default this function sorts the array alphabetically (if we don't provide any parameter). It would work for you if you want to sort a string/character array in ascending order. If you want to change the order of sorting, you might need to use reverse function like:
array.reverse();
In case of sorting array with numbers, the default sort would give some unexpected surprises. It would again sort alphabetically so number like 5 would come after a number like 23. To get away with this and do the correct sort, you can define your own sort function and pass the function name as parameter to array.sort(). For example, following function would sort the numbers in ascending order:
function sortorder(a, b){
return a-b;
}
return a-b;
}
If you want to change the order to descending:
function sortorder(a, b){
return b-a;
}
return b-a;
}
Its as simple as that. You can even return -ve or 0 or +ve value randomly to randomize (or shuffle) the array. But beware of the performance impact of this.
No comments:
Post a Comment