We can use JavaScript to sort an array of strings by using the JavaScript Array sort() method.
var colors = ["Red", "Green", "Blue", "Orange","Yellow"];
colors.sort();
Let’s take a look at a simple example below.
Let’s say we have a simple array of colors and we want to sort them. To do this we simply need to use the JavaScript sort() method.
var colors = ["red","blue","green","yellow","orange","purple","pink","black"];
colors.sort();
In this example, the resulting array “colors” would now contain the following:
We can also sort an array of strings that have number values using the sort() method.
var numbers = ["5","6","1","8","4","9","2","3"];
numbers.sort();
Which would result in the following:
Let’s take a look at an example using HTML.
Using JavaScript to Sort an Array of Strings With a Click
In this example, we will have a large array of CSS color names that are supported by most browsers. We will set up some HTML to let the user see all the colors contained in the array. We will then have a button that will sort the array of strings.
Here is the HTML set up:
Sort colors
In the JavaScript portion of this example, we will first create the HTML span elements that will each contain their own color. We will do this by iterating over the cssColors array using a for loop. The cssColors array will contain 140+ String color names. We will add the colors to div “#colorDiv” using the appendChild() method.
We will then add an onclick event that will run the function to create the HTML, and then also sort the array of colors using the sort() method. We will then clear the HTML div containing our colors by changing the innerHTML to nothing, and remake it using the updated array.
Here is the JavaScript code:
var cssColors = ["LightGoldenRodYellow","Sienna","Brown","Salmon","DarkRed","SkyBlue","Bisque","Snow","DarkGray","YellowGreen","Coral","Aqua","BurlyWood","LightSeaGreen","MediumOrchid","Chocolate","BlueViolet","CornflowerBlue","LemonChiffon","PapayaWhip","Cyan","DarkBlue","Maroon","DarkGoldenRod","BlanchedAlmond","DarkGrey","Olive","Tomato","Tan","LimeGreen","SandyBrown","DarkOrchid","Azure","DarkSalmon","MidnightBlue","NavajoWhite","White","DarkSlateGrey","RosyBrown","Pink","DeepPink","DeepSkyBlue","DimGray","DimGrey","DodgerBlue","Purple","FloralWhite","ForestGreen","PeachPuff","Gainsboro","GhostWhite","MistyRose","GoldenRod","Gray","PaleGreen","Green","GreenYellow","HoneyDew","WhiteSmoke","IndianRed","Yellow","Ivory","Khaki","Orange","LavenderBlush","LawnGreen","Cornsilk","LightBlue","LightCoral","LightCyan","AliceBlue","LightGray","LightGrey","LightGreen","LightPink","LightSalmon","CadetBlue","LightSkyBlue","LightSlateGray","LightSlateGrey","LightSteelBlue","LightYellow","Lime","DarkOliveGreen","Linen","Magenta","DarkCyan","MediumAquaMarine","MediumBlue","Chartreuse","MediumPurple","MediumSeaGreen","MediumSlateBlue","MediumSpringGreen","MediumTurquoise","MediumVioletRed","DarkSeaGreen","MintCream","Gold","Moccasin","DarkSlateBlue","Navy","OldLace","DarkGreen","OliveDrab","Lavender","OrangeRed","Orchid","PaleGoldenRod","Grey","PaleTurquoise","PaleVioletRed","Crimson","Fuchsia","Peru","DarkViolet","Plum","PowderBlue","FireBrick","RebeccaPurple","Red","DarkTurquoise","RoyalBlue","SaddleBrown","Aquamarine","DarkOrange","SeaGreen","SeaShell","AntiqueWhite","Silver","Beige","SlateBlue","SlateGray","SlateGrey","Black","SpringGreen","SteelBlue","DarkMagenta","Teal","Thistle","DarkKhaki","Turquoise","Violet","Wheat","DarkSlateGray","HotPink","Indigo","Blue"];
//Populate HTML with colors in cssColors array
for (var i = 0; i < cssColors.length; i++) {
var newColor = document.createElement('span');
newColor.textContent = cssColors[i];
document.getElementById("colorDiv").appendChild(newColor);
}
function sortColors() {
//Sort colors
cssColors.sort();
//Clear HTML of old colors
document.getElementById("colorDiv").innerHTML = "";
//Populate HTML with colors in cssColors array after sorting colors
for (var i = 0; i < cssColors.length; i++) {
var newColor = document.createElement('span');
newColor.textContent = cssColors[i];
document.getElementById("colorDiv").appendChild(newColor);
}
}
The final code and output for this example is below:
Code Output:
Full Code:
Sort colors
<script>
var cssColors = ["LightGoldenRodYellow","Sienna","Brown","Salmon","DarkRed","SkyBlue","Bisque","Snow","DarkGray","YellowGreen","Coral","Aqua","BurlyWood","LightSeaGreen","MediumOrchid","Chocolate","BlueViolet","CornflowerBlue","LemonChiffon","PapayaWhip","Cyan","DarkBlue","Maroon","DarkGoldenRod","BlanchedAlmond","DarkGrey","Olive","Tomato","Tan","LimeGreen","SandyBrown","DarkOrchid","Azure","DarkSalmon","MidnightBlue","NavajoWhite","White","DarkSlateGrey","RosyBrown","Pink","DeepPink","DeepSkyBlue","DimGray","DimGrey","DodgerBlue","Purple","FloralWhite","ForestGreen","PeachPuff","Gainsboro","GhostWhite","MistyRose","GoldenRod","Gray","PaleGreen","Green","GreenYellow","HoneyDew","WhiteSmoke","IndianRed","Yellow","Ivory","Khaki","Orange","LavenderBlush","LawnGreen","Cornsilk","LightBlue","LightCoral","LightCyan","AliceBlue","LightGray","LightGrey","LightGreen","LightPink","LightSalmon","CadetBlue","LightSkyBlue","LightSlateGray","LightSlateGrey","LightSteelBlue","LightYellow","Lime","DarkOliveGreen","Linen","Magenta","DarkCyan","MediumAquaMarine","MediumBlue","Chartreuse","MediumPurple","MediumSeaGreen","MediumSlateBlue","MediumSpringGreen","MediumTurquoise","MediumVioletRed","DarkSeaGreen","MintCream","Gold","Moccasin","DarkSlateBlue","Navy","OldLace","DarkGreen","OliveDrab","Lavender","OrangeRed","Orchid","PaleGoldenRod","Grey","PaleTurquoise","PaleVioletRed","Crimson","Fuchsia","Peru","DarkViolet","Plum","PowderBlue","FireBrick","RebeccaPurple","Red","DarkTurquoise","RoyalBlue","SaddleBrown","Aquamarine","DarkOrange","SeaGreen","SeaShell","AntiqueWhite","Silver","Beige","SlateBlue","SlateGray","SlateGrey","Black","SpringGreen","SteelBlue","DarkMagenta","Teal","Thistle","DarkKhaki","Turquoise","Violet","Wheat","DarkSlateGray","HotPink","Indigo","Blue"];
for (var i = 0; i < cssColors.length; i++) {
var newColor = document.createElement('span');
newColor.textContent = cssColors[i];
document.getElementById("colorDiv").appendChild(newColor);
}
function sortColors() {
cssColors.sort();
document.getElementById("colorDiv").innerHTML = "";
for (var i = 0; i < cssColors.length; i++) {
var newColor = document.createElement('span');
newColor.textContent = cssColors[i];
document.getElementById("colorDiv").appendChild(newColor);
}
}
</script>
Hopefully this article has been useful for you to understand how to use JavaScript to sort an array of strings .