Sort array by string length JavaScript | Example code

A Given string array, do Sort array by string length JavaScript.

Use Array.sort method to sort the array. A sorting function that considers the length of string as the sorting criteria can be used as follows:

A given array like this:

After sorting, the output array should be:

Solution

JavaScript sorting array string by len Example

HTML example code:

  • For ascending sort order: a.length - b.length
  • For descending sort order: b.length - a.length

Output:

Do comment if you have any doubts and suggestion on this JS array topic.

Note: All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.