• 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 Reverse an Array

Using JavaScript to Reverse an Array

August 19, 2022 Leave a Comment

We can use JavaScript to reverse an array by simply using the JavaScript Array reverse() method.

someArray.reverse();

Let’s see the reverse array in use with a simple example.

var numbersArray = [1,2,3,4,5,6,7,8,9,10];

//Reverse the order of the array
numbersArray.reverse();
console.log(numbersArray);

#Output:
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

Notice that using the reverse method on an array will change the values of the array the method is called on.

Let’s take a look at an example using HTML.

Using JavaScript to Reverse 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 reverse 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="reverseColors()">Reverse 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 reverse the array of colors using the reverse() 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 = ["AliceBlue","AntiqueWhite","Aqua","Aquamarine","Azure","Beige","Bisque","Black","BlanchedAlmond","Blue","BlueViolet","Brown","BurlyWood","CadetBlue","Chartreuse","Chocolate","Coral","CornflowerBlue","Cornsilk","Crimson","Cyan","DarkBlue","DarkCyan","DarkGoldenRod","DarkGray","DarkGrey","DarkGreen","DarkKhaki","DarkMagenta","DarkOliveGreen","DarkOrange","DarkOrchid","DarkRed","DarkSalmon","DarkSeaGreen","DarkSlateBlue","DarkSlateGray","DarkSlateGrey","DarkTurquoise","DarkViolet","DeepPink","DeepSkyBlue","DimGray","DimGrey","DodgerBlue","FireBrick","FloralWhite","ForestGreen","Fuchsia","Gainsboro","GhostWhite","Gold","GoldenRod","Gray","Grey","Green","GreenYellow","HoneyDew","HotPink","IndianRed","Indigo","Ivory","Khaki","Lavender","LavenderBlush","LawnGreen","LemonChiffon","LightBlue","LightCoral","LightCyan","LightGoldenRodYellow","LightGray","LightGrey","LightGreen","LightPink","LightSalmon","LightSeaGreen","LightSkyBlue","LightSlateGray","LightSlateGrey","LightSteelBlue","LightYellow","Lime","LimeGreen","Linen","Magenta","Maroon","MediumAquaMarine","MediumBlue","MediumOrchid","MediumPurple","MediumSeaGreen","MediumSlateBlue","MediumSpringGreen","MediumTurquoise","MediumVioletRed","MidnightBlue","MintCream","MistyRose","Moccasin","NavajoWhite","Navy","OldLace","Olive","OliveDrab","Orange","OrangeRed","Orchid","PaleGoldenRod","PaleGreen","PaleTurquoise","PaleVioletRed","PapayaWhip","PeachPuff","Peru","Pink","Plum","PowderBlue","Purple","RebeccaPurple","Red","RosyBrown","RoyalBlue","SaddleBrown","Salmon","SandyBrown","SeaGreen","SeaShell","Sienna","Silver","SkyBlue","SlateBlue","SlateGray","SlateGrey","Snow","SpringGreen","SteelBlue","Tan","Teal","Thistle","Tomato","Turquoise","Violet","Wheat","White","WhiteSmoke","Yellow","YellowGreen"];

//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 reverseColors() {
  
  //Reverse colors
  cssColors.reverse();
  
  //Clear HTML of old colors
  document.getElementById("colorDiv").innerHTML = "";
  
  //Populate HTML with colors in cssColors array after reversing 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:

Reverse 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="reverseColors()">Reverse colors</div>
  <div id="results"></div>
</div>

<script>

var cssColors = ["AliceBlue","AntiqueWhite","Aqua","Aquamarine","Azure","Beige","Bisque","Black","BlanchedAlmond","Blue","BlueViolet","Brown","BurlyWood","CadetBlue","Chartreuse","Chocolate","Coral","CornflowerBlue","Cornsilk","Crimson","Cyan","DarkBlue","DarkCyan","DarkGoldenRod","DarkGray","DarkGrey","DarkGreen","DarkKhaki","DarkMagenta","DarkOliveGreen","DarkOrange","DarkOrchid","DarkRed","DarkSalmon","DarkSeaGreen","DarkSlateBlue","DarkSlateGray","DarkSlateGrey","DarkTurquoise","DarkViolet","DeepPink","DeepSkyBlue","DimGray","DimGrey","DodgerBlue","FireBrick","FloralWhite","ForestGreen","Fuchsia","Gainsboro","GhostWhite","Gold","GoldenRod","Gray","Grey","Green","GreenYellow","HoneyDew","HotPink","IndianRed","Indigo","Ivory","Khaki","Lavender","LavenderBlush","LawnGreen","LemonChiffon","LightBlue","LightCoral","LightCyan","LightGoldenRodYellow","LightGray","LightGrey","LightGreen","LightPink","LightSalmon","LightSeaGreen","LightSkyBlue","LightSlateGray","LightSlateGrey","LightSteelBlue","LightYellow","Lime","LimeGreen","Linen","Magenta","Maroon","MediumAquaMarine","MediumBlue","MediumOrchid","MediumPurple","MediumSeaGreen","MediumSlateBlue","MediumSpringGreen","MediumTurquoise","MediumVioletRed","MidnightBlue","MintCream","MistyRose","Moccasin","NavajoWhite","Navy","OldLace","Olive","OliveDrab","Orange","OrangeRed","Orchid","PaleGoldenRod","PaleGreen","PaleTurquoise","PaleVioletRed","PapayaWhip","PeachPuff","Peru","Pink","Plum","PowderBlue","Purple","RebeccaPurple","Red","RosyBrown","RoyalBlue","SaddleBrown","Salmon","SandyBrown","SeaGreen","SeaShell","Sienna","Silver","SkyBlue","SlateBlue","SlateGray","SlateGrey","Snow","SpringGreen","SteelBlue","Tan","Teal","Thistle","Tomato","Turquoise","Violet","Wheat","White","WhiteSmoke","Yellow","YellowGreen"];

for (var i = 0; i < cssColors.length; i++) {
  var newColor = document.createElement('span');
  newColor.textContent = cssColors[i];
  document.getElementById("colorDiv").appendChild(newColor);
}

function reverseColors() {
  cssColors.reverse();
  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 helpful for you to learn how to use JavaScript to reverse an array.

Other Articles You'll Also Like:

  • 1.  Remove Multiple Characters From String in JavaScript
  • 2.  JavaScript Random Number – How to Generate a Random Number In JavaScript
  • 3.  Using JavaScript to Check if Variable is a String
  • 4.  Adding an Underline with JavaScript
  • 5.  Using JavaScript to Get Date Format in yyyy-mm-dd hh mm ss
  • 6.  JavaScript continue statement – Skip Iterations in Loop Based on Conditions
  • 7.  JavaScript Sorted Map – How to Sort a Map by Keys or Values
  • 8.  Changing the Background Image of a div in JavaScript
  • 9.  Using JavaScript to Show and Hide a Div
  • 10.  Using JavaScript to Check if String Contains Letters

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