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:
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:
Full Code:
<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.