Home > Mobile >  Javascript Iterate elements of a first array at the position of another second array
Javascript Iterate elements of a first array at the position of another second array

Time:05-29

hello i have the following code

let names = ["josh","tony","daniel"];  
let arrayplaces = ["30", "60", "90"];

names.forEach((elem, indexed) => {
  const num2 = arrayplaces[indexed];
  console.log('The user '   elem   ' iterated in place '   num2);
});

What I'm looking for is to iterate through all the elements of the first array into the first element of the second array, ending with the first one and continuing until it goes through the entire second array.

Example of the expected output:

The user josh iterated in place 30
The user tony iterated in place 30
The user daniel iterated in place 30

The user josh iterated in place 60
The user tony iterated in place 60
The user daniel iterated in place 60

The user josh iterated in place 90
The user tony iterated in place 90
The user daniel iterated in place 90

Does anyone know how I can do this?

CodePudding user response:

You can do this by nesting loop both the array.

let names = ["josh","tony","daniel"];  
let arrayplaces = ["30", "60", "90"];

arrayplaces.forEach((element)=>{
  names.forEach((elem) => {
  console.log('The user '   elem   ' iterated in place '   element);
  });
 console.log('');
});

CodePudding user response:

You just should eterate every value of arrayplaces with every name. You should use 2 cycles to do that.

const names = ['josh', 'tony', 'daniel'];
const arrayplaces = ['30', '60', '90'];

names.forEach((elem, indexed) => {
  names.forEach((elem2) => {
    const num2 = arrayplaces[indexed];
    console.log(`The user ${elem2} iterated in place ${num2}`);
  });
});

CodePudding user response:

You need to loop over both arrays.

for (let place of arrayplaces) {
    for (let name of names) {
        console.log(`The user ${name} iterated in place ${place}`)
    }
    console.log('\n')
}
  • Related