Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

forEach loop through two arrays at the same time in javascript [duplicate]

I want to build a for loop that iterates through two variables at the same time. n is an array and j goes from 0 to 16.

var n = [1,2,3,5,7,8,9,11,12,13,14,16,17,18,20,21,22]; var m = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];  m.forEach(k => {     n.forEach(i => {         console.log(i, k)     }); }; 

The final result should output:

1,0 2,1 3,2 5,3 (...) 

Unfortunately this loop doesn't do that for some reason as it repeats every number 17 times.

What am I missing here?

like image 941
FilipeTeixeira Avatar asked Sep 12 '19 08:09

FilipeTeixeira


People also ask

How do I iterate over two arrays 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. 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.

Does forEach run synchronously?

Note: forEach expects a synchronous function. forEach does not wait for promises. Make sure you are aware of the implications while using promises (or async functions) as forEach callback.

Is forEach faster than for JavaScript?

forEach is almost the same as for or for..of , only slower. There's not much performance difference between the two loops, and you can use whatever better fit's the algorithm. Unlike in AssemblyScript, micro-optimizations of the for loop don't make sense for arrays in JavaScript.

Is JavaScript forEach parallel?

JavaScript is, for the most part, single-threaded. There are no parallel operations like that in the language.


1 Answers

Use the second parameter forEach accepts instead, which will be the current index you're iterating over:

n = [1,2,3,5,7,8,9,11,12,13,14,16,17,18,20,21,22];    n.forEach((element, index) => {    console.log(element, index);  });

If you have two separate arrays to begin with, in each iteration, access the [index] property of the other array:

var n = [1, 2, 3, 5, 7, 8, 9, 11, 12, 13, 14, 16, 17, 18, 20, 21, 22];  var m = [0, 1, 2, 3, 4, 5, 6, 7,  8,  9,  10, 11, 12, 13, 14, 15, 16];    n.forEach((num1, index) => {    const num2 = m[index];    console.log(num1, num2);  });
like image 174
CertainPerformance Avatar answered Oct 13 '22 03:10

CertainPerformance