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
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> </head> <body> <pre id="output"></pre> <script> var arr = ['raspberry', 'nut', 'cherry', 'apple']; displayOutput = 'Input Array : ' + arr + '\n'; var sortedArr = arr.sort((a, b) => a.length - b.length); displayOutput += 'Sorted Array : ' + sortedArr + '\n'; document.getElementById("output").innerHTML = displayOutput; </script> </body> </html>
Conclusion
In this JavaScript Tutorial, we learned how to sort an array of strings based on length using sort() method.