A few examples of how to sort different types of javascript arrays.
Array.sort()
sorts values as strings by default. This works well for strings, but not as well for sorting numbers.
const names = ['Mike', 'Joe', 'Fred', 'Dan'];
names.sort();
console.log(names);
// output: ["Dan", "Fred", "Joe", "Mike"]
You can see it sorts them alphabetically. Nice!
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
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:
a
and b
) which are meant to represent items to sorta
and b
:
b
before a
a
before b
a
and b
the sameNow 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