var arr = [5, 2, 1, -10, 8];
arr.sort(function(a, b) {
console.log(a,b)
return b - a;
}) ; // 8, 5, 2, 1, -10
How does this callback work?
What is the principle of choice a and b?
Please explain this particular example from the inside.
output console.log (at first, please explain this output ):
5 2
2 1
1 -10
-10 8
1 8
2 8
5 8
The sort() method allows you to sort elements of an array in place. Besides returning the sorted array, the sort() method changes the positions of the elements in the original array. By default, the sort() method sorts the array elements in ascending order with the smallest value first and largest value last.
The easiest way to sort is with the sorted(list) function, which takes a list and returns a new list with those elements in sorted order. The original list is not changed. It's most common to pass a list into the sorted() function, but in fact it can take as input any sort of iterable collection.
The JavaScript array sort() is used to sort array elements. By default, the array will sort in ascending order, but we can change it. This method will change the original array. We can also provide our comparing function to implement custom sorting.
Then, when you call sort(), with your custom compare function, the compare function is called on pairs in your to-be-sorted list, to determine the proper ordering. Simply subtracting b from a will always return greater than zero if a is larger than b, 0 if they are equal, or less than zero if a is less than b.
It depends on the implementation. This actual implementation, looks like an insertion sort, with this amount of data (it could be different, like with Chrome, and the different implementation for less than 10 items or more items), is going from index zero to the end and if a swap has not taken place at the last two items, then it stops, otherwise it goes backwards to index zero.
Basically it tests and changes in this order
5 2 1 -10 8 original order
5 2
2 1
1 -10
-10 8 swap
8 -10
1 8 swap
8 1
2 8 swap
8 2
5 8 swap
8 5 2 1 -10 result
A more complex sorting shows better what is going on, with two greater values, which need to move to the other side of the array
8 9 1 2 3 4 original array
8 9
9 1 swap
1 9
8 1 swap
1 8
9 2 swap
2 9
8 2 swap
2 8
1 2
9 3 swap
3 9
8 3 swap
3 8
2 3
9 4 swap
4 9
8 4 swap
4 8
3 4
1 2 3 4 8 9 result
Live example, does not work in all user agents (eg not in Edge, but in Chrome)
var array = [8, 9, 1, 2, 3, 4];
console.log(JSON.stringify(array));
array.sort(function (a, b) {
console.log(a , b, JSON.stringify(array));
return a - b;
});
console.log(JSON.stringify(array));
.as-console-wrapper { max-height: 100% !important; top: 0; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With