27.4 C
Gujarat
HomeJavascripthow to loop through two arrays in javascript

how to loop through two arrays in javascript

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
how to loop through two arrays in javascript

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.

You may also like:

Adminhttps://rocoderes.com
Rocoderes is a blog you can learn HTML, CSS, JavaScript, React Js and Python along with creative coding stuff and free source code files.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

15,000FansLike
5,000FollowersFollow
535FollowersFollow
- Advertisment -spot_img

Subscribe to our newsletter

To be updated with all the latest news, offers and special announcements.

Most Popular