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