+ 4
Can anyone tell me plz why does subtracting a - b sort the numbers in numerical order?
var myArray = [10, 44, 32, 100, 0, 44, 3, 4]; document.write(myArray); // 10, 44, 32, 100, 0, 44, 3, 4 myArray.sort(); document.write(myArray); // 0,10,100,3,32,4,44,44 myArray.sort(function (a, b) { return a - b; }); document.write(myArray); // 0,3,4,10,32,44,44,100 And also How do all the numbers get sorted into proper order if the function is only examining 2 numbers at a time? (i.e. a and b)
2 Respuestas
+ 1
1. Substraction gives negative(b>a), positive(a>b) or zero(a==b) value depending on relation between numbers.
2. Learn some basic sorting algorithms like bubble sort https://www.w3resource.com/javascript-exercises/javascript-function-exercise-24.php.
+ 1
Actually I knew about bubble sort before but little confused about having function as argument in sort() anyway TQ for Ur answer ..