Tell us what’s happening:
For the code below, which part of it is considered the
“callback” function.
They introduced this idea a few lessons ago and keep referring to
it and have not received nor found a good explanation online so I can understand
what is the “callback” function.
Thanks for the help!
Your code so far
function ascendingOrder(arr) {
return arr.sort(function(a, b) {
return a - b;
});
}
ascendingOrder([1, 5, 2, 3, 4]);
// Returns [1, 2, 3, 4, 5]
function reverseAlpha(arr) {
return arr.sort(function(a, b) {
return a === b ? 0 : a < b ? 1 : -1;
});
}
reverseAlpha(['l', 'h', 'z', 'b', 's']);
// Returns ['z', 's', 'l', 'h', 'b']
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:83.0) Gecko/20100101 Firefox/83.0.
Challenge: Sort an Array Alphabetically using the sort Method
So the callback function was already pointed out to you earlier but it would help to know why you have to use this callback when sorting numbers.
Let’s look at this example
let arr = ["b", "e", "a"]
arr.sort();
// result would be ["a", "b", "e"]
// obviously that is correct, right?
But what if we did this example
let arr = [9,2,10]
arr.sort();
// you might think the result should be this [2,9,10]
// but actually it is this [10, 2, 9]
So you are probably wondering why this is the case.
Well when you use sort() it actually only looks at the first letter of a word or in this case the first digit. So that is why 10 comes before 2 because the computer is comparing the first digit of 10 (which is 1) with 2.
That is where the callback function comes in.
You only need to use this callback function with numbers. You can just use arr.sort() when dealing with letters and words.