Skip to content

JS sort alphabetically | Examples code

  • by

Use sort() method to sort array alphabetically in JS. By default, the sort() method sorts the values as strings in alphabetical only.

JS sort alphabetically Example

HTML example code Sort an array alphabetically:-

Example 1

<html>
<body>

	<script>
		var fruits = ["B", "C", "D", "A"];
		var sf = fruits.sort();

		console.log(sf);
		
	</script>
</body>
</html>

Output:

JS sort alphabetically

Example 2

Alphabetical order array JavaScript

<script>
		var foo = ["B", "C", "D", "A"];

		foo.sort(function(a, b) {
			return a === b ? 0 : a < b ? -1 : 1;
		});

		console.log(foo);
</script>

Example 3

Using compare function and show sort alphabetically array in the webpage.

<html>
<body>

	<p id="demo"></p>
	<script>
		var foo = ["B", "C", "D", "A"];

		//sorts arrays of numbers
		function myFunction() {
			foo.sort(function(a, b){return a-b});
			document.getElementById("demo").innerHTML = foo;
		}
		myFunction();
	</script>
</body>
</html>

Do comment if you have any doubts and suggestions on this JavaScript Array code.

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