Skip to content

Sort array by string length JavaScript | Example code

  • by

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading