Categories
Vue Answers

How to use forEach to loop through two arrays at the same time in JavaScript?

Spread the love

Sometimes, we want to use forEach to loop through two arrays at the same time in JavaScript.

In this article, we’ll look at how to use forEach to loop through two arrays at the same time in JavaScript.

How to use forEach to loop through two arrays at the same time in JavaScript?

To use forEach to loop through two arrays at the same time in JavaScript, we can use the index parameter of the forEach callback to get the element with the same index from the 2nd array.

For instance, we write

const n = [1, 2, 3, 5, 7, 8, 9, 11, 12, 13];
const m = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

n.forEach((num1, index) => {
  const num2 = m[index];
  console.log(num1, num2);
});

to call n.forEach with a callback that gets the element from m with the same index and assign it to num2.

And then we log the value of num1 and num2.

Conclusion

To use forEach to loop through two arrays at the same time in JavaScript, we can use the index parameter of the forEach callback to get the element with the same index from the 2nd array.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *