This a task from a JS workshop I am working on:
let numbers = [50, 10, 40, 30, 20];
function compareNumbers(a, b) {
let retVal = 0;
if (a < b) {
retVal = -1;
} else if(a > b) {
retVal = 1;
}
return retVal;
}
let sorted = numbers.sort(compareNumbers);
console.log(sorted); // [10, 20, 30, 40, 50]
I am asked to do the following:
A. Try to modify the above piece of code to make it as short as possible. Suggestions:
- use an anonymous function;
- use an arrow function;
- consider skipping the
if
statement.
This is not an exercise from freeCodeCamp and it is not a homework or a test from elsewhere. Anyway, I did this:
let numbers = [50, 10, 40, 30, 20];
let fix = (a, b) => (a < b)? retVal = -1 : ((a > b)? retVal = 1 : 0)
let sorted = numbers.sort(fix);
console.log(sorted);
But upon looking at the solution for this task this is what’s offered:
let numbers = [50, 10, 40, 30, 20];
let sorted = numbers.sort((a, b) => a - b);
console.log(sorted);
I frankly don’t get it… I don’t understand the answer nor, like most of the time, I don’t know what am I doing here…
If anyone could offer me an explanation I would appreciate it.