The sort()
method in Javascript is used to sort elements in an array. Normally, sort() orders elements alphabetically as strings. However, when we want to sort numerical values or do some sort of custom sorting, the sort() method accepts a callback function which is specifically designed to handle this kind of situation. The syntax for the callback function is
(a, b) => {}
, where a
and b
are the two elements being compared.
In other to understand how sort() works with a callback function, there are certain rules you need to know
- If a is less than b, then a should come before b
- If a is greater than b, then a should come after b
- If a is equal to b, then the positions of a and b should not change.
This might look confusing at first, but let me give an example that explains these rules better.
const numbers = [20, 100, 60, 40, 80];
numbers.sort((a, b) => a - b);
console.log(numbers); // Output: [20, 40, 60, 80, 100]
Let's break this example down step by step
Initially when the code runs, our array is
[20, 100, 60, 40, 80]
. When the code reaches where the array is sorted, it continually compares a and b until the whole array is sorted properly.The first time the numbers array is sorted, a is 20 and b = 100, remember the 1st rule says if a is less than b, then a should come before b, meaning that here in our numbers array, 20 should come before 100. The new array will be
[20, 100, 60, 40, 80]
, which is still the same thing, no changes yetThe next time the sort runs, a is now 100 and b is now 60, since a is greater than b here (rule 2), we are going to put a after b. Therefore, our new array will now be
[20, 60, 100, 40, 80]
Again when the sort runs, a is now 100 and b is now 40, since a is still greater than b, we are going to put a after b. Therefore, our new array will now be
[20, 40, 60, 100, 80]
. if you noticed, we should have had[20, 60, 40, 100, 80]
as the new array, but since the sort process has already started, sort() knows it is meant to reposition the elements correctly, so it properly arranges the numbers array for us, and puts 40 before 60For the last time, the sort runs again, and compares the last a and b values together which are 100 and 80, and since a is still greater than b, it puts a after b, our new array then becomes
[20, 40, 60, 80, 100]
This is basically how the callback function in the sort()
method works, it's not so complicated. It runs like a loop, arranging each element in our array until it has properly arranged everything. It is very useful to use, and it can come in handy when sort() on it's own is not enough.
I write about what I learn from Javascript and React, you can reach out or follow me on Twitter and Linkedin for more content like this
Top comments (0)