When you're working with a string array, a common operation is to sort the array by the length of the strings.
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.
sort() method on the
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']
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.
Leave us a message!