JavaScript – Sort a String Array based on String Length

To sort strings in an array based on length in JavaScript, call sort() method on this string array and pass a comparison function to sort() method, such that the comparison happens for the length of elements.

arr.sort((a, b) => a.length - b.length)

Example

In the following example, we have taken a string array in arr. We sort this array using sort() method and store the resulting array in sortedArr. We pass a comparison function to sort() method, where it takes two elements (a, b) as arguments, and returns the difference of their lengths.

index.html

ADVERTISEMENT

Conclusion

In this JavaScript Tutorial, we learned how to sort an array of strings based on length using sort() method.