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 Solid
- Getting Started with Express
- Git Tutorial: Learn how to use Version Control
- Best Visual Studio Code Extensions for 2022
- How to deploy a PHP app using Docker
- Getting Started with Deno
- Using Puppeteer and Jest for End-to-End Testing
- Getting Started with Handlebars.js
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Using Push.js to Display Web Browser Notifications
- Getting Started with React
- Setting Up a Local Web Server using Node.js