Updated June 30, 2023
Introduction to JavaScript Iterate Array
JavaScript has a lot of Array iteration patterns that help developers write clean and read code. In Javascript, we have many methods for an array that iterates for each element in an array and can be used according to our purpose of iteration. You can even iterate an array using a simple for loop in javascript. However, it is better to use some available functions provided they fulfill your purpose.
Here is the list of the functions that iterate or call a function repetitively for each element in the array in JavaScript.
- forEach()
- map()
- filter()
- reduce()
- reduceRight()
- every()
- some()
- indexOf()
- lastIndexOf()
- find()
- findIndex()
Ways of Iterating Array in JavaScript
There are multiple ways for iterating arrays, which are given below:
1. Array.forEach()
Syntax:
array.forEach(callback(currentValue [, currentIndex [, array]])[, thisArgument]);
- array: It is the array on which we are iterating.
- callback: This is the first parameter, a function that is a predicate that returns true if we want that particular element in the desired array or else false.
- currentValue: This is the second parameter, the element in the original array currently being processed.
- currentIndex: It is the parameter that specifies the index of the current element being processed. array -It is the array on which we are applying the filter.
- thisArgument: This is the value that is to be used as this value in the callback function.
Example:
Code:
<!DOCTYPE html>
<html>
<body>
<h3>Demonstration of JavaScript Array.forEach() used for iterating on each element of an array to call a callback or function</h3>
<p id="sampleDemo"></p>
<script>
var listOfFruits = "";
var fruits = ["apple", "mango", "banana", "grapes", "watermelon","jackfruit","papaya"]; fruits.forEach(callMyFunc);
document.getElementById("sampleDemo").innerHTML = listOfFruits;
function callMyFunc(valueOfElement, indexOfElement, arrayOfFruits) { listOfFruits = listOfFruits + valueOfElement + "<br>";
}
</script>
</body>
</html>
The output of the above code gives a list of fruits as each fruit callMyFunc function is called, and its name is appended to the variable listOfFruits, which is finally displayed after calling callMyfunc for each element of the fruits array.
Output:
2. Map, Filter, Reduce, and reduceRight Methods
The map function iterates for each array element and calls a function for each element to create a new array that contains all the manipulated or changed values. It does not change the original array leaving it intact. The filter method returns a new array with elements that pass the predicate or test mentioned in the callback function. The map function does not alter or affect the original array. You can use the “reduce” and “reduce right” functions to calculate a cumulative value from all elements. Its manipulation depends on the code written in the callback or function called for each element. The key difference in both is the direction of traversing the elements. The reduceRight function processes the items from right to left.
Example:
Code:
<!DOCTYPE html>
<html>
<body>
<h3>Demonstration of JavaScript Array Map, filter, reduce and reduceRight methods</h3>
<p id="sampleDemo1"></p>
<p id="sampleDemo2"></p>
<p id="sampleDemo3"></p>
<p id="sampleDemo4"></p>
<script>
var basicNumbers = [1,2,3,4,5,6,7,8,9];
var doubleValues = basicNumbers.map(doubleTheArr);
document.getElementById("sampleDemo1").innerHTML = "The double valued array is " + doubleValues;
var evenValues = basicNumbers.filter(filterEvenElements);
document.getElementById("sampleDemo2").innerHTML = "The even numbered elements in array are " + evenValues;
var simpleProduct = basicNumbers.reduceRight(multiply);
document.getElementById("sampleDemo3").innerHTML = "The product by using reduce is " + simpleProduct;
var product = basicNumbers.reduceRight(multiply); document.getElementById("sampleDemo4").innerHTML = "The product by using reduceRight is "
+ product;
function doubleTheArr(currentValue, currentIndex, array) { return currentValue * 2;
}
function filterEvenElements(currentIndex, currentIndex, array) {
return currentIndex % 2;
}
function multiply(initialOrPreviouslyReturnedValue, currentValue, currentIndex, array) { return initialOrPreviouslyReturnedValue + currentValue;
}
</script>
</body>
</html>
Output:
3. Every and Some Methods
Some methods are equivalent to their work’s AND and OR logical operations. Both functions return a boolean value depending on whether the elements of the passed array pass certain conditions specified in the callback function. In the case of every, if all the array elements pass the test, then only it returns true or otherwise false. At the same time, in the case of some, even if some of the elements pass the test specified in the callback, then it returns true or otherwise false. Let us see one example related to both of them.
Code:
<!DOCTYPE html>
<html>
<body>
<h3>Demonstration of JavaScript Array Every And Some Functions</h3>
<p id="sampleDemo1"></p>
<p id="sampleDemo2"></p>
<script>
var basicNumbers = [-1,-2,-3,-4,-5,-6,-7,-8,-9,1,2,3,4,5,6,7,8,9];
var whetherPositiveNumbers = basicNumbers.every(checkForPositiveNumber);
document.getElementById("sampleDemo1").innerHTML = "Are all array elements are positive integers? Answer is " + whetherPositiveNumbers;
var whetherSomePositiveNumbers = basicNumbers.some(checkForPositiveNumber);
document.getElementById("sampleDemo2").innerHTML = "Are some array elements are positive integers? Answer is " + whetherSomePositiveNumbers;
function checkForPositiveNumber(currentValue, currentIndex, array) { return currentValue >0;
}
</script>
</body>
</html>
Output:
4. indexOf, lastIndexOf, Find, findIndex Methods
indexOf and lastIndexOf return the index where the passed element is present. The difference is indexOf() returns the first found element position. In contrast, lastIndexOf finds the location of the last occurrence of that element.find. To check if a specific element is present in an array, use the Findindex function. Find returns the value of the element while findIndex returns its location, i.e., index.
Code:
<!DOCTYPE html>
<html>
<body>
<h3>Demonstration of JavaScript Array indexOf, lastIndexOf, find, findIndex methods</h3>
<p id="sampleDemo1"></p>
<p id="sampleDemo2"></p>
<p id="sampleDemo3"></p>
<p id="sampleDemo4"></p>
<script>
var fruits = ["apple", "mango", "banana", "grapes", "watermelon","jackfruit","papaya","jackfruit"]; var firstFound = fruits.indexOf("jackfruit");
document.getElementById("sampleDemo1").innerHTML = "We found the jackfruit at location "+firstFound;
var lastLocation = fruits.lastIndexOf("jackfruit");
document.getElementById("sampleDemo2").innerHTML = "We found the jackfruit last at location "+lastLocation;
var whetherFound = fruits.find(checkForWatermelon);
document.getElementById("sampleDemo3").innerHTML = "We found the watermelon at location "+whetherFound;
var foundIndex = fruits.findIndex(checkForWatermelon);
document.getElementById("sampleDemo4").innerHTML = "We found the watermelon last at location "+foundIndex;
function checkForWatermelon(currentValue, currentIndex, array) { return currentValue == "watermelon";
}
</script>
</body>
</html>
Output:
Recommended Articles
This is a guide to JavaScript Iterate Array. Here we discuss the introduction and methods of JavaScript iterate array, which include forEach()map(), filter(), reduceRight(), etc. You may also look at the following articles to learn more –