Could you please explain the logic behind Step 111 (Building a Pyramid Generator)?

The .push() method makes sense but the .unshift() method makes me confuse. Could you please help me how .unshift() method makes the pyramid inverted?

Thank you!

can you share the code you are asking about? the unshift method adds stuff at the beginning of the array, without the context in which it is used it’s impossible to say its relation to the pyramid

please post the code not a screenshot

When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (').

Gotcha, thank you! Here:

const character = "#";
const count = 8;
const rows = [];

function padRow(rowNumber, rowCount) {
  return " ".repeat(rowCount - rowNumber) + character.repeat(2 * rowNumber - 1) + " ".repeat(rowCount - rowNumber);
}

for (let i = 1; i <= count; i++) {
  rows.push(padRow(i, count));
}

let result = ""

for (const row of rows) {
  result = result + row + "\n";
}

console.log(result);

That gives me a pyramid and when you replace .push() with .unshift(), the pyramid becomes inverted:

for (let i = 1; i <= count; i++) {
  rows.unshift(padRow(i, count));
}

you have the first line.
push add the second line after the first line, the pyramid grows larger going down.
unshift add the second line before the first line, the pyramid grows larger going up

Thank you! I also used the visual simulator and I got it finally. Really thank you!

1 Like