How does sort function work in JavaScript, along with compare function -
as asked: how sort function work in javascript, along compare function? if have array, , array.sort(compare) written in book if compare function returns a-b (two indices of array) works based on fact whether result greater 0, less 0 or equal 0. but, how work? not work out.
the "compare" function must take 2 arguments, referred a , b. make compare function return 0, greater 0, or less 0, based on these values, a , b.
- return greater 0 if a greater b
- return 0 if a equals b
- return less 0 if a less b
with these 3 return values, , 2 arguments, possible write compare function can sort type of input data type, or complex data structures.
then, when call sort(), custom compare function, compare function called on pairs in to-be-sorted list, determine proper ordering.
lets walk through simple example... suppose you're sorting numbers, have simple compare function:
function compare(a,b) { return - b; } simply subtracting b return greater 0 if larger b, 0 if equal, or less 0 if less b. meets requirements compare function.
now lets suppose our list of numbers sort:
var numbers = [1,5,3.14]; when call numbers.sort(compare), internally execute:
compare(1,5); // returns -4, less b compare(1,3.14); // return -2.14, less b compare(5,3.14); // returns 1.86, greater b if you've ever done manual sorting or alphabetizing, you've done precisely same thing, without realizing it. though may have dozens or hundreds of items compare, you're comparing 2 numbers (or author's last names, or whatever) @ time. going through or short list of 3 numbers again, you'd start comparing first 2 numbers:
- is 1 greater or less 5? less than, put these 2 numbers in our list: 1,5
- is 3.14 greater or less 1? greater than, goes after 1 in new list
- is 3.14 greater or less 5 in our new list? less than, goes before 5. our new list [1,3.14,5]
because can provide own compare() function, possible sort arbitrarily complex data, not numbers.
Comments
Post a Comment