Examples of sorting different types of javascript arrays
By Mike Sallese ·
What sort does by default
Array.sort() sorts values as strings by default. This works well for strings, but not as well for sorting numbers.
Default sort for strings
const names = ['Mike', 'Joe', 'Fred', 'Dan'];
names.sort();
console.log(names);
// output: ["Dan", "Fred", "Joe", "Mike"]
You can see it sorts them alphabetically. Nice!
Default sort for numbers
How about for numbers:
const numbers = [2, 30, 45, 1, 100];
numbers.sort();
console.log(numbers);
// output: [1, 100, 2, 30, 45]
As you can see, it’s sorting them by strings still! Probably not what we expected
Custom sort for numbers
Let’s write our own custom sort to sort the numbers how we expected:
const numbers = [2, 30, 45, 1, 100];
numbers.sort(function(a, b) {
if (a > b) {
return 1
} else {
return -1
}
});
// output: [1, 2, 30, 45, 100]
Much better! So what did we do there? Let’s break it down:
- We passed a compare function to sort, which is an optional parameter
- The compare function gives you access to two variables (
aandb) which are meant to represent items to sort - Here are the rules for
aandb:- Return value is greater than 0: sort
bbeforea - Return value is less than 0: sort
abeforeb - Return value is equal to 0: keep the order of
aandbthe same
- Return value is greater than 0: sort
Now that you get the idea, you can write much more robust sorting functions comparing a vs b, which could even be objects with properties.
For other javascript examples: https://www.mikesallese.me/tags/javascript
About the author
Mike Sallese. I build Scribbl, an AI note taker with no bot in the call, and a few other pieces of software. Off the computer I am building a straw bale workshop.
X · Medium · GitHub · articles on other sites