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:

arr = ['ab', 'abcdefgh', 'xyz', 'pqrs']

After sorting, the output array should be:

sort_arry = [ "abcdefgh", "pqrs", "xyz", "ab" ]

Solution

array.sort(function(a, b){return b.length - a.length});

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
<!DOCTYPE html>
<html>
<body>
	
	<script>
		arr = ['ab', 'abcdefgh', 'xyz', 'pqrs']
		
		arr.sort(function(a, b){
			return b.length - a.length
		});

		console.log(arr);

	</script>
	
</body>
</html>

Output:

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

Note: The 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.