Home > Software engineering >  NodeJs Array.join with text on each part of the array
NodeJs Array.join with text on each part of the array

Time:10-17

So I want to make something that console logs

Name1 Is Ready
Name2 Is Ready
Name3 Is ready

and each name is in an array(so Something like this)

let array = []

array.push("Name1", "Name2", "Name3")

I can't seem to get it to work as I want since when I try to console log it with

console.log(array.join("\n")   "is Ready")

I get

Name1
Name2
Name3is ready

Is there any way to make it console log like

Name1 Is Ready
Name2 Is Ready
Name3 Is ready

CodePudding user response:

You have to loop through the array to achieve what you're looking for

like this

array.forEach(name => {
    console.log(name   "is Ready")
})

CodePudding user response:

const array = ["Name1", "Name2", "Name3"]

array.forEach(node => {
  console.log(node   " is Ready!")
})
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

If you have a number of elements all with the same prefix you can create an array, and then map over the array and join the elements into a string.

const arr = new Array(3)
  .fill(0)
  .map((_, i) => `Name${i   1}`);

const str = arr.map(el => `${el} is ready`).join('\n');

console.log(str);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related