Hello guys, In this article we will learn how to loop through two arrays in javascript at same time. we are use forEach to loop through two arrays.
How to loop through two arrays in javascript Using forEach ?
To use forEach to loop through 2 arrays at a similar time in JavaScript, we are able to use the index parameter of the forEach callback to get the part with a similar index from the second array. If both arrays have the same length then you can use index to log elements from other array.
var array1 = [1, 2, 3, 4];
var array2 = [5, 6, 7, 8];
array1.forEach(function(item, index){
console.log(item, array2[index])
});
Output:
1 5
2 6
3 7
4 8
Here we have two array array1 and array2.These two array have same length. to call array1.forEach with a callback that gets the element from array2 with the same index.
Conclusion
To use forEach to loop through 2 arrays at an similar time in JavaScript, we will use the index parameter of the forEach and get the same index from the second array.