const arr = [3, 89, 1, 120, 23];
console.log(arr.sort((a, b) => a - b));
The code above sorts the array. However, how does sort know that a = current index and that b = next index??? We never specify to sort what they are and to what they're equal to.
And after that, how does .sort figure out that the returned value from that anonymous arrow function means that the value need to be moved? Example: [1, 2]
sort((a, b) => a - b))
sort((1, 2) => 1 - 2))
sort((1, 2) => -1))
sort(-1));
See? How does .sort know what to do with -1?
I've been Googling and YouTubing for the past 2 hours and can't find the answer... :(
However, how does sort know that a = current index and that b = next index?
No, a
is current value, b
is next value.
The sort
function you see is not just run once, it runs again and again, depending on which length your array has.
In your case, in the first run, a
equals 3
and b
equals 89
. And the second run, a
equals 3
, b
equals 1
.
The sort
function is work for an array of strings, so if you need to sort an array of strings, just use array.sort()
Compare function
is required when you need to sort a numeric array.
If not, it gets the wrong result: "25" is bigger than "100", because "2" is bigger than "1".
Compare function
just return three kinds of number:
a
less than b
a
equals b
a
greater than b
So, you can more clearly return inside the Compare function
like this:
if(a === b)
return 0;
if(a < b)
return -1;
return 1;
But, simpler, you can a using a trick, you just need to return ab
to determine whether a
is greater than b
or not.
See more: JavaScript Sorting Arrays
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.