Build a Pyramid Generator - Build a Pyramid Generator

Tell us what’s happening:

This code is working, it just seems kind of awkward. Is there a better way to do this?

Your code so far

function pyramid (pattern, rowNum, isInverted) {
  const finalArr = [];
  let finalStr = "";

  //First row to base off of
  const firstRow = new Array(rowNum - 1).fill(" ");
  firstRow.push(pattern);
  finalArr.push(firstRow);

  //Next rows
  let lastRow = [...firstRow];
  for (let i = 1; i < rowNum; i++) {
    let nextRow = [...lastRow];
    nextRow.shift();
    nextRow.push(pattern);
    nextRow.push(pattern);
    finalArr.push(nextRow);
    lastRow = [...nextRow];
  }

  //Invert if needed
  if (isInverted) finalArr.reverse();

  //Return
  for (const arr of finalArr) {
    finalStr += "\n" + arr.join("");
  }
  finalStr += "\n";
  return finalStr;
}

console.log(pyramid("o", 4, true));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36

Challenge Information:

Build a Pyramid Generator - Build a Pyramid Generator

Welcome back to the forum @facundotabarez0

What part of the code feels awkward?

Happy coding

Hello!
I feel like arrays shouldn’t be necesarry to begin with. And even with arrays, it feels wierd to handle the first row independently from the rest of them. It just feels like it’s not optimal nor elegant.
Thanks for responding!

Why is that? What made you choose to use an array here?

The first row is different in that it’s the first and none of the others are. Can you explain a bit more about what seems weird about the way you handle the first row (and how it’s different than the others and why?)

Also, I suggest this video: