How to Sort an Array by String Length in JavaScript
Table of Contents
When you're working with a string array, a common operation is to sort the array by the length of the strings.
In this post, we'll learn how you can sort an array of strings by their length in JavaScript.
Sorting an array of strings by their length
First, consider this example string array:
JAVASCRIPTconst strings = ["hello", "world", "how", "are", "you"];
Here we have an array of five strings, all of various lengths, perfect to illustrate sorting.
The way we are going to sort this array is by using the built-in JavaScript sort()
method on the Array
object.
This method takes in a function that is called for each element in the array and compares two elements against each other.
Since we want to sort by an element's string length, we need to define a function that takes in two elements and returns a number.
Let's see how we can implement this function:
JAVASCRIPTconst strings = ["hello", "world", "how", "are", "you"];
const ascending = strings.sort((a, b) => a.length - b.length);
console.log(ascending); // ['how', 'are', 'you', 'hello', 'world']
You can also sort it by descending order by simply flipping the order of the elements being compared:
JAVASCRIPTconst strings = ["hello", "world", "how", "are", "you"];
const descending = strings.sort((a, b) => b.length - a.length);
console.log(descending); // ['world', 'hello', 'you', 'are', 'how']
Conclusion
In this post, we saw how you can efficiently sort a string array by their length. We also learned how to sort them either ascending or descending, useful in cases where you want to sort by a specific criteria.
Hopefully, this post has been helpful to you and you can use it a reference for your own work.
Happy coding!
- Getting Started with TypeScript
- How to Install Node on Windows, macOS and Linux
- Getting Started with Electron
- How to Serve Static Files with Nginx and Docker
- How to Set Up Cron Jobs in Linux
- Getting Started with Deno
- How to deploy a MySQL Server using Docker
- How to Scrape the Web using Node.js and Puppeteer
- Getting User Location using JavaScript's Geolocation API
- Getting Started with Moment.js
- Creating a Twitter bot with Node.js
- Setting Up Stylus CSS Preprocessor