What will happen if we define variables let a,b then call arr.sort(a,b => a > b)?
I have done both ways but there was something wrong with this way… what goes behind the scene I coouldn’t get…!?
Your code so far
function alphabeticalOrder(arr) {
// Add your code below this line
let a,b;
return arr;
// Add your code above this line
}
console.log(alphabeticalOrder([91,89,3, 5, 1, 0, 9, 2]));
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:65.0) Gecko/20100101 Firefox/65.0.
Sort expect a positive, negative or 0 value - with a comparison you are returning negative (false) or positive (true) values, and never negative, as such you will get unexpected results
Sorry to say that, I think You haven’t got what the question is about?
It is correct but I wanted to test it with separate defined variables let a; let b;
If we do it by parameters a, b it works but not with separate defined variables.
I understand, but that is different
let’s see the combined code
function alphabeticalOrder(arr) {
// Add your code below this line
let a,b;
return arr.sort(a,b => a > b);
// Add your code above this line
}
console.log(alphabeticalOrder([91,89,3, 5, 1, 0, 9, 2]));
// 0,1,2,3,5,89,9,91
see the output
try the code yourself and notice the numbers 89 vs 9
The error is inside the sort method
Your callback never returns a negative number, so it will never sort correctly
If you use the following you don’t get the error
arr.sort(function(a, b) {
return a - b;
});
Please read the documentation
This is from the documentation
If compareFunction(a, b) is less than 0, sort a to an index lower than b (i.e. a comes first).
If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.
If compareFunction(a, b) is greater than 0, sort b to an index lower than a (i.e. b comes first).
compareFunction(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments. If inconsistent results are returned then the sort order is undefined.
No, the error is just that you are not using parenthesis around parameters with arrow function - try changing just that and you will see, when you have more than one parameter you must use parenthesis around it
Anyway, you should use the sort method returning positive, negative, 0 - you are lucky because the browser you are using still support the true/false thing, not all do, so on different browsers you would have different results