The Basics of Sorting in JavaScript

Welcome to my blog 👋🏽
I'm a Front-End Developer with a passion for learning!
I write about Programming 👩🏽💻 and Productivity Tips ✅
Search for a command to run...

Welcome to my blog 👋🏽
I'm a Front-End Developer with a passion for learning!
I write about Programming 👩🏽💻 and Productivity Tips ✅
No comments yet. Be the first to comment.
Although my experience is primarily with front-end development, my current job is affording me the opportunity to do more full-stack work. Naturally, this meant that I needed to explore the different database GUIs available on the market. Here is a l...

A Note on the Series: Fast Fridays 🏎 is a series where you will find fast, short, and sweet tips/hacks that you may or may not be aware of. I will try to provide these (fairly) regularly on Fridays. In this Fast Friday tip, I'll explain how to crea...

Over the past year, I’ve started incorporating a Git GUI into my workflow. I still reach for the terminal about 90% of the time, but I’ve found that a GUI can really shine when it comes to things like viewing diffs, checking stashes, or resolving mer...

Simplifying Branch Management with Git Worktree

With all the AI tools popping up these days, I figured I'd try out some speech-to-text software in an attempt to boost my productivity. I've been hearing a lot about “developing at the speed of thought”, so here's a list of the top speech-to-text sof...

By default, the sort() method in JavaScript will sort an array in place and works by looping through each item in the array and comparing each item two at a time until the array is sorted. To do this, it converts the array to strings and sorts them alphabetically in ascending order. This will only work well if there is a simple array of case-insensitive strings. For 99% of the time, you will need to write a custom compare function.
undefined elements are sorted to the end of the array, with no call to the compare function.a and b are two elements being compared, thena is sorted before b.b is sorted before a.a and b unchanged with respect to each other but sorted with respect to all different elements.const compare = (a, b) => {
if (a < b) return -1;
if (a > b) return 1;
return 0; // a must be equal to b
}
This is by far the simplest and most succinct of all the sorting method types so providing a code example should explain itself.
const sortByNumbersAsc = (a, b) => a - b //Ascending sort
const sortByNumbersDesc = (a, b) => b - a //Descending sort
Typically you will convert the strings you want to compare to a common case so use toLowerCase() or toUpperCase(). Whatever suits your fancy.
Good article on sorting Strings
//Ascending String sort
const sortByStringAsc = (a,b) => {
const aLower = a.toLowerCase();
const bLower = b.toLowerCase();
return aLower > bLower ? 1 : bLower > aLower ? -1 : 0;
}
//Descending String sort
const sortByStringDesc = (a,b) => {
const aLower = a.toLowerCase();
const bLower = b.toLowerCase();
return aLower > bLower ? -1 : bLower > aLower ? 1 : 0;
}
This is probably the most realistic way you will need to sort. Thankfully it’s not that much different from sorting a String or Number. Actually, it’s pretty much the same except instead of just the generic a & b comparison, you will need to explicitly state which object properties you want to compare against.
const cars = [
{ make: "Nissan", year: 2017 },
{ make: "Chevrolet", year: 2001 },
{ make: "BMW", year: 2010 }
];
//Numeric sort - sort by year ascending
cars.sort((a,b) => a.year - b.year)
//String sort - sort by car make 🚗 ascending
const sortByStringAsc = (a,b) => {
const aMake = a.make.toLowerCase();
const bMake = b.make.toLowerCase();
return aMake > bMake ? 1 : bMake > aMake ? -1 : 0;
}
I've provided examples of descending sorts in the respective code blocks but I wanted to write a little blurb about this as well.
If you need to sort in descending order, just swap the return 1 in the comparison function with return -1 for both a & b conditionals. Or put another way, it’s basically the reverse of the ascending sort logic.
Another way I’ve seen suggested to sort in descending order is to use the reverse() method.
Because the sort() method sorts an array in place, it will directly manipulate the array that is being sorted, therefore making it mutable 👎🏽. Due to this, you want to make sure you are working off of a copy of the array or using a package like immer to keep things immutable.
[Photo by UX Indonesia on Unsplash]