• 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
  • VBA
  • About
You are here: Home / JavaScript / How to Iterate through an Array Using JavaScript

How to Iterate through an Array Using JavaScript

February 11, 2022 Leave a Comment

To iterate through an array using JavaScript we can use a for loop. Here is a simple setup of how to use a for loop to iterate through an array:

for (var i = 0; i < someArray.length; i++) {
  //Do something with array "someArray"
}

Let’s take a look at a simple example below.


Let’s say we have a simple array of colors and we want to see if the color white is included in the array of colors. To do this we will want to iterate through the array and check each color to see if it is “white”. We can do it easily with a for loop.

var colors = ["red","blue","green","yellow","orange","purple","pink","black"];
var colorFound = false;
for (var i = 0; i < colors.length; i++) {
  if (colors[i] == "white"){
    //The color has been found.
    colorFound = true;
  }
}

If at the end of this loop, colorFound is “true”, then white was in the array of colors. If colorFound is false, then white is not in the array.

In this example, colorFound would have the value of “false”.

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

Iterating through an Array to see if it Contains a String

In this example, we will have a large array of CSS color names that are supported by all browsers. We will set up some HTML to let the user see all the colors contained in the array. We will also have an input field that will let the user enter a color to see if it is contained in the array. If it is, we will display that it is. Otherwise, we will display that it is not.

Here is the HTML set up:

<style>#colorDiv span { margin-right: 10px; display: inline-block; }</style>
<div id="colorDiv"></div>
<div id="div1">
  <label for="userinput">Check if color is in list above:</label>
  <input type="text" id="new-color" name="userinput">
  <div id="click-me" onclick="checkColor()">Check color</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.

In the next part of this example, we will get the user inputted color from the input field.

We will finally check if the color is contained in the array of colors we have(cssColors), and if it is, display that it is. Otherwise we will display that it is not in the #results div using the textContent property.

Notice we will also use the toLowerCase method to make it so the color is not case sensitive when searching.

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);
}

//Next get the user input, and check if the color is in our array
function checkColor() {
  var colorFound = false;
  var uInput = document.getElementById("new-color").value;
  var userInput = uInput.toLowerCase();
  //iterate over array and check for the user color
  for (var i = 0; i < cssColors.length; i++) {
    if( cssColors[i].toLowerCase() == userInput ){
      colorFound = true;
    }
  }
  if( colorFound == true ){
    document.getElementById("results").textContent = uInput + " IS in the array";
  } else {
    document.getElementById("results").textContent = uInput + " is NOT in the array";
  }
}

The final code and output for this example is below:

Code Output:


Check color

Full Code:

<style>#colorDiv span { margin-right: 10px; display: inline-block; }</style>
<div id="colorDiv"></div>
<div id="div1">
  <label for="userinput">Check if color is in list above:</label>
  <input type="text" id="new-color" name="userinput">
  <div id="click-me" onclick="checkColor()">Check color</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"];

//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);
}

//Next get the user input, and check if the color is in our array
function checkColor() {
  var colorFound = false;
  var uInput = document.getElementById("new-color").value;
  var userInput = uInput.toLowerCase();
  //iterate over array and check for the user color
  for (var i = 0; i < cssColors.length; i++) {
    if( cssColors[i].toLowerCase() == userInput ){
      colorFound = true;
    }
  }
  if( colorFound == true ){
    document.getElementById("results").textContent = uInput + " IS in the array";
  } else {
    document.getElementById("results").textContent = uInput + " is NOT in the array";
  }
}

</script>

Hopefully this article has been useful for you to understand how to iterate through an array using JavaScript.

Other Articles You'll Also Like:

  • 1.  Using JavaScript to get the Last Element in Array
  • 2.  clearInterval JavaScript – How the clearInterval() Method in JavaScript Works
  • 3.  Set Checkbox as Checked in JavaScript
  • 4.  JavaScript Exponent – Exponentiate Numbers with Math.pow()
  • 5.  Remove Word From String In JavaScript
  • 6.  Using JavaScript to Get the Max Value in an Array
  • 7.  JavaScript Sorted Map – How to Sort a Map by Keys or Values
  • 8.  Using JavaScript to Subtract Days From a Date
  • 9.  JavaScript Map Size – Find Length of JavaScript Map
  • 10.  Using JavaScript to Remove All Pipe Characters From String

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

The Programming Expert is a compilation of hundreds of code snippets to help you find solutions to your problems in Python, JavaScript, PHP, HTML, SAS, and more.

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 © 2022 · The Programming Expert · About · Privacy Policy