Sorting numbers in JavaScript | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Sorting numbers in JavaScript

Hi everyone. I’m relatively new to JavaScript programming. I have some code that sorts numbers in an Array. I know that it works, but I would really like to know how the function actually sorts the numbers. ——-code starts——- const numbers = [40,21,56,70,201,8]; let val = numbers.sort(function(x , y){ return x - y; }); console.log(val);

19th Mar 2018, 9:21 AM
Graham Hartle
Graham Hartle - avatar
2 Answers
+ 10
🔹x and y are two of the values in the array, that you compare so Javascript can sort them. 🔹return x-y 👉 If x-y: ⤵️ 🔸Less than 0: "x" is sorted to be a lower index than "y". 🔸Zero: "x" and "y" are considered equal, and no sorting is performed. 🔸Greater than 0: "y" is sorted to be a lower index than "x". 🔹The function is called lots of times to determine where each element in the array is compared to all the others. The exact number of times the function is called depends on the number of elements in the array and their original order.
19th Mar 2018, 9:43 AM
LukArToDo
LukArToDo - avatar
+ 8
@Graham Feel free to ask all you need, SL community will help you. Good luck 😉
19th Mar 2018, 9:52 AM
LukArToDo
LukArToDo - avatar