Home > Back-end >  single iteration over multidimensional javascript array
single iteration over multidimensional javascript array

Time:12-17

for example:

var myArray = [
 [id1, "john", 30],
 [id2, "smith", 60],    
 [id3, "kate", 90],
];

I would like with one loop to get data based on position in array

I need to get something like :

john is 30

smith is 60

kate is 90

CodePudding user response:

Map through the array and insert the values into the string:

var myArray = [
 [1, "john", 30],
 [2, "smith", 60],    
 [3, "kate", 90],
];

const res = myArray.map(e => `${e[1]} is ${e[2]}`).join('\n')
console.log(res)

CodePudding user response:

You could always just iterate to get a reference for placement in the array and then hardcode values into the code regarding values inside that reference.

var myArray = [
 ["john", 30],
 ["smith", 60],    
 ["kate", 90],
];

for (let i = 0; i < myArray.length; i  ) {
  console.log(`${myArray[i][0]} is ${myArray[i][1]}`)
}

If you want to get them in the same line, use a string.

var myArray = [
 ["john", 30],
 ["smith", 60],    
 ["kate", 90],
];

let str = ''
for (let i = 0; i < myArray.length; i  ) {
  str  = `${myArray[i][0]} is ${myArray[i][1]} `
}
console.log(str)

CodePudding user response:

A simpler way to solve this is by using map

myArray.map(person => `${person[1]} is ${person[2]}`)
  • Related