Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
163
rated 0 times [  169] [ 6]  / answers: 1 / hits: 85224  / 5 Years ago, thu, september 12, 2019, 12:00:00

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?


More From » for-loop

 Answers
31

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);
});




[#51661] Thursday, September 5, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaylynbrynnk

Total Points: 706
Total Questions: 98
Total Answers: 91

Location: Israel
Member since Thu, Jan 7, 2021
3 Years ago
;