Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

183
Views
Shorter Way of Prinitng Triangle Patterns JavaScript

I'm trying to find a shorter way to print a right-triangle and an isosceles triangle without using that many nested loops. Please help, here is my code so far, it works I just have trouble finding a shorter way to write it:

//right-triangle
let triangleStr = "";
let num = 5;
for (let i = 1; i <= num; i++) {
  for (let j = 0; j < num - i; j++) {
    triangleStr += " ";
  }
  for (let k = 0; k < i; k++) {
    triangleStr += "*";
  }
  triangleStr += "\n";
}
console.log(triangleStr);

//isosceles-triangle
triangleString = "";
for (let i = 1; i <= num; i++) {
  for (let j = 1; j <= num - i; j++) {
    triangleString += " ";
  }
  for (let k = 1; k <= 2 * i - 1; k++) {
    triangleString += "*";
  }
  triangleString += "\n";
}
console.log(triangleString);

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

If you want to use only one loop, you can use repeat() method in ECMAScript6 or higher.

For Right triangle:

const line = 5;
let rightTriangle = "";
for (let l = 1; l <= line ; l++) {
    const indent = line-l;
    rightTriangle += `${" ".repeat(indent)}${"*".repeat(l)}${"\n"}`;
}
console.log(rightTriangle);

For Isosceles triangle:

const line = 5;
let isoscelesTriangle = "";
for (let l = 1; l <= line ; l++) {
    const indent = line - l;
    isoscelesTriangle += `${" ".repeat(indent)}${"*".repeat(2*l-1)}${"\n"}`;
}
console.log(isoscelesTriangle);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!