+ 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);
2 Respostas
+ 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.
+ 8
@Graham
Feel free to ask all you need, SL community will help you.
Good luck 😉