+ 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