How to Sort an Array by String Length in JavaScript

Updated onbyAlan Morel
How to Sort an Array by String Length in JavaScript

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:

const 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:

const 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:

const 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!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.