Home > Net >  How can I pass multiple const's of .entries into one "for" loop
How can I pass multiple const's of .entries into one "for" loop

Time:06-08

I have this code:

for (const [index, value] of txtfile1.entries()) {
  console.log(`${index}: ${value}`);
}

And I need to pass this loop one more txt file to make something like this:

for (const [index, value] of txtfile1.entries()) && (const [index2, value2] of txtfile2.entries()) {
  console.log(`${index}: ${value} and ${index2}: ${value2}`);
}

So my goal is to use data from two different txt files in the same loop. Pls help!

CodePudding user response:

you can't loop over multiple things directly in a for loop. Use a loop that provides indexes, then use that to index into both arrays.

const e1 = txtfile1.entries();
const e2 = txtfile2.entries();
e1.forEach(([key, value], index) => {
  const [key2, value2] = e2[index];
  console.log(`${key}: ${value} and ${key2}: ${value2}`);
});

CodePudding user response:

Maybe you can take longest entries and loop like this

const e1 = ["A1","A2","A3"]
const e2 = ["B1","B2"];
const longest = e1.length > e2.length ? e1 : e2
for (const [index] of longest.entries()) {
  console.log(`${index}: ${e1[index] || ""} and ${index}: ${e2[index] || ""}`);
}

output:

0: A1 and 0: B1 
1: A2 and 1: B2 
2: A3 and 2:  

CodePudding user response:

So I've got a comment by Jupri: cant you just use nested :

for (const [index, value] of txtfile1.entries()) for (const [index2, value2] of txtfile2.entries()) {console.log(${index}: ${value} and ${index2}: ${value2})}

And it worked, thanks a lot to Jupri and everyone else who responded.

  • Related