Learn Basic Algorithmic Thinking by Building a Number Sorter - Step 44

Tell us what’s happening:

Im sohard-stuck on this one, wrote three if statements before that, but it didnt help so i reseted the lesson, feeling so lost that i started writing chatGPT for answers, but i understand that i shouldnt, so now im writing this, mb someone can help me understand it and not ctrl+c ctrl+v, i dont understand what a, b stands for, how do i write this comparing THIS small without if and why it wont work, and what it means by implicit return? return 0? return?

Your code so far

<!-- file: index.html -->

/* file: styles.css */

/* file: script.js */
// User Editable Region

  const sortedValues = inputValues.sort((a, b) => {

  });

// User Editable Region

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 OPR/115.0.0.0

Challenge Information:

Learn Basic Algorithmic Thinking by Building a Number Sorter - Step 44

Hi @artemkirpotenko

The first thing is to start with the return keyword

Your callback function should use an explicit return.

Keeping in mind that you want the numbers to be sorted in ascending order (smallest to largest), return a single subtraction calculation using a and b that will correctly sort the numbers with the above logic.

a and b are parameters.

After the return keyword insert the calculation. This will sort the numbers from lowest to highest.

Happy coding

return and what after it?I dont get it.Why return a - b works?

a minus b

The return keyword finds the difference between two numbers. If the difference is negative that means a is smaller than b. If difference is greater than 0 then a is bigger than b. If the difference is 0 then the values are the same.

The .sort() method then works it way though an array sorting the numbers from smallest to largest using the above logic.

3 Likes

So sort() works like this:for example, if I have 5 light bulbs, then first the first and second bulbs light up, then the first and third, then the first and fourth, then the first and fifth, and then the second and third, and so on in a circle?And the logic is, if i can concatenate something and get a number bigger than 0 then i should replace those number because the first one is bigger.Am i right?

Or this way?.If i keep up with the same analogy it will be so that, 1 and 2 bulb ,then 2 and 3 bulb , then 3 and 4 bulb , then 4 and 5 bulb are being compared.If we imagine it, like every bulb has its brightness and needs to be sorted from worst to best.Or its bubble sort?

the implementation of sort depends on the environment, it could work in any of those ways. But if an element has to be sorted before or after an other depends on the result from the callback