+ 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 š