• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

The Programming Expert

Solving All of Your Programming Headaches

  • HTML
  • JavaScript
  • jQuery
  • PHP
  • Python
  • SAS
  • Ruby
  • About
You are here: Home / JavaScript / Using JavaScript to Sort an Array of Strings

Using JavaScript to Sort an Array of Strings

March 3, 2022 Leave a Comment

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:

[“black”, “blue”, “green” , “orange” , “pink” , “purple” , “red”, “yellow”]

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:

1,2,3,4,5,6,8,9

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:

<style>#colorDiv span { margin-right: 10px; display: inline-block; }</style>
<div id="colorDiv"></div>
<div id="div1">
  <div id="click-me" onclick="sortColors()">Sort colors</div>
  <div id="results"></div>
</div>

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:

Sort colors

Full Code:

<style>#colorDiv span { margin-right: 10px; display: inline-block; }</style>
<div id="colorDiv"></div>
<div id="div1">
  <div id="click-me" onclick="sortColors()">Sort colors</div>
  <div id="results"></div>
</div>

<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 .

Other Articles You'll Also Like:

  • 1.  Using JavaScript to Convert String to Integer
  • 2.  Convert a Set to Array in JavaScript
  • 3.  Using JavaScript to Set the Id of an Element
  • 4.  JavaScript slice – How to Get a Substring From a String
  • 5.  How to Uncheck All Checkboxes in JavaScript
  • 6.  Reverse a String in JavaScript
  • 7.  clearInterval JavaScript – How the clearInterval() Method in JavaScript Works
  • 8.  How to Check if a String Contains Vowels in JavaScript
  • 9.  Using JavaScript to Check if String Contains Numbers
  • 10.  JavaScript String endsWith Method

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

About The Programming Expert

the programming expert main image

Welcome to The Programming Expert. We are a group of US-based programming professionals who have helped companies build, maintain, and improve everything from simple websites to large-scale projects.

We built The Programming Expert to help you solve your programming problems with useful coding methods and functions in various programming languages.

Search

Learn Coding from Experts on Udemy

Looking to boost your skills and learn how to become a programming expert?

Check out the links below to view Udemy courses for learning to program in the following languages:

Copyright © 2023 · The Programming Expert · About · Privacy Policy