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 Svelte
- Getting Started with Express
- Create an RSS Reader in Node
- How to Set Up Cron Jobs in Linux
- How to build a Discord bot using TypeScript
- How to deploy a PHP app using Docker
- How to deploy a Deno app using Docker
- How to deploy a Node app using Docker
- Learn how to use v-model with a custom Vue component
- Using Push.js to Display Web Browser Notifications
- Building a Real-Time Note-Taking App with Vue and Firebase
- Getting Started with React