-4

My output is

1
1
2
1
2
3

The output I am looking for is

1 1 2 1 2 3 1 2 3 4 1 2 3 4 5

var x,y;
for(x=1; x <= 5; x++){
    for (y=1; y <= x; y++) {
        console.log(y)
    }
}

3
  • 3
    create a variable outside the loop: var str = "", then inside loop just do: str += valueYouWantToConcatenate. Then log it after the loops Commented Jul 29, 2019 at 19:48
  • 2
    I don't see much difference from the your actual output and expected output, can you elaborate? Commented Jul 29, 2019 at 19:49
  • @KevinDiTraglia,the question title: "How to concatenate string in iteration loop" Commented Jul 29, 2019 at 19:50

5 Answers 5

1

You could take a single loop with a part variable and one for the full string.

Then you need to add a space only if the string is not empty and add in each loop the new value and the actual part to the full string.

var i,
    part = '',
    full = '';
    
for (i = 1; i <= 5; i++) {
    part += (part && ' ') + i;
    full += (full && ' ') + part;
}

console.log(full);

Sign up to request clarification or add additional context in comments.

1 Comment

Thats quite elegant (not sure if its more efficient, as string concatenation time also grows ...)
0

Try with this code:

var x,y,z='';
for(x=1; x <= 5; x++){
    for (y=1; y <= x; y++) {
        z = z + y + ' ';
    }
}
console.log(z);

Comments

0

Try the snippet below:

var str = ''

for (let i = 1; i <= 5; i++) {
  for (let j = 1; j <= i; j++) {
    str += `${j} `
  }
}

console.log(str)

Comments

0

This should work for you:

var x, y, concatenatedString = '';

for(x = 1; x <= 5; x++) {
    for (y=1; y <= x; y++) {
        concatenatedString += `${y} `
    }
}
console.log(concatenatedString)


Comments

-1

You are console logging each time which puts it on a new line. It's a better idea to store numbers in an array and then print out one by one.

var x, y, myArray[];
for (x = 1; x <= 5; x++) {
  for (y = 1; y <= x; y++) {
    myString += y.toString() + " ";
  }
}
console.log(myString);

You could also place numbers in an array and output one by one.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.