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 which is a function that is a predicate which returns true if we want that particular element in the desired array else false.
- currentValue: This is the second parameter which is the element in the original array which is currently being processed.
- currentIndex: It is the parameter that specifies the index of the current element being processed. array -It 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 fruits array.
Output:
2. Map, Filter, Reduce and reduceRight Methods
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 who pass the predicate or test mentioned in the callback function. Similar to the map function, the original array is not muted or changed. Reduce and reduce right functions are used when we want to achieve a cumulative value that is retrieved from all the elements and its manipulation depends on the code written in the callback or function called for each element. The key difference in both of them is just the direction of traversing the elements. In the case of the reduceRight function, items are traversed 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
Every and some methods are equivalent to the AND and OR logical operations in its working. Both the functions return a boolean value depending on whether the elements of the passed array pass certain conditions specified in the callback function. In case of every, if all the elements of the array pass the test then only it returns true otherwise false while in case of some, even if some of the elements pass the test specified in callback then it returns true 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 while lastIndexOf finds the location of the last occurrence of that element.find and findIndex is used to check whether the array contains a specific element with the help of a function. find returns the value of 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 –
39 Online Courses | 24 Hands-on Projects | 230+ Hours | Verifiable Certificate of Completion
4.5
View Course
Related Courses