JavaScript Algorithm for Pyramids

Experimenting with simple algorithms brought me to this code. I'm curious if anyone has a more concise version in JavaScript for displaying a pyramid:

const max= 30;
let row = 1;

for (let i = 1; i < max; i += 2) {
    console.log(' '.repeat(max / 2 - row) + '*'.repeat(i))
    row++;
}

Answer №1

Is this the code you were looking for?

let s = '*'
for(let p=15;p--;) 
  {
  console.log( ' '.repeat(p) + s)
  s += '**'
  }
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

Here is a solution using the map function:

function createPyramid(height) {
  return Array(height).fill('*')
    .map((current, index) =>
      ' '.repeat(height - index) +
      current.repeat(index).split('').join(' ') +
      ' '.repeat(height - index))
    .join('\n');
}
console.log(createPyramid(30));

Answer №3

If you're looking for a more concise method, try using a while loop.

I found this solution particularly useful from reading the response by Mister Jojo.

let s = '*',
    p = 15;
    
while (p--) {
    console.log(' '.repeat(p) + s)
    s += '**';
}
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №4

printPattern(Array.from({length:15},(_,i)=>"*".repeat(i*2+1).padStart(15+i)).join`\n`);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

An issue has arisen when trying to fetch and parse data using React and JavaScript

I am currently facing some challenges with fetching data from an API and displaying it using React. I have encountered errors and I am struggling with parsing the JSON response from the API. I believe that converting the response into an array may help res ...

Retrieving an array of various responses using Axios

My current code includes a function that retrieves exchange rates for various stocks: export const getRates = (symbole1, symbole2, symbole3) => { const res = [] axios.all([ axios.get(`${baseUrl}/${symbole1}`), axios.get(`${ ...

Deploy a web application using JavaScript and HTML to Heroku platform

I noticed that when I visit the Heroku dashboard, there is an option to create an app using Node.js, but not JavaScript. This raises a question for me - if I want to upload my locally created JavaScript/HTML5 app to Heroku, do I need to select Node.js or ...

Experiencing a glitch with the Realtime Database feature on Firebase

// db.js file import * as firebase from "firebase/app" import "firebase/database" const config = { apiKey: "" ... } const db = firebase.initializeApp(config) export default db // App.vue ...

Encountering a Console warning while working with the Material UI menu. Seeking advice on how to resolve this issue as I am integrating HTML within a text

Caution: PropType validation failed. The prop text provided to LinkMenuItem is invalid as it should be a string, not an object. Please review the render method of Menu. Below is the code snippet: var menuItems = [ // text is not valid text { route: &ap ...

Cross-Origin Request Sharing (CORS) problem encountered while making an API call with

My current challenge involves calling an API that returns data in XML format as a response. While testing the .htm file on my local machine, I encountered the following error. https://i.stack.imgur.com/FsvZ0.png Similarly, running it from the codepen.io ...

Issue encountered while constructing my application (utilizing the "yarn run build" command and in Vercel)

Encountered an error during the build process, whether on the server or locally. This issue arises when using package managers like yarn, npm, and others. The error specifically points to a problem in the CSS file, but it only occurs in the production bu ...

How to achieve horizontal auto-scrolling in an image gallery with jQuery?

Hey there, I'm currently working on an Image Gallery project. I have arranged thumbnails horizontally in a div below the main images. Take a look at this snapshot img. My goal is to have the thumbnails scroll along with the main pictures as the user ...

Employing v-btn for navigating to a different route depending on whether a specific condition is satisfied

Is there a way to prevent this button from redirecting to the specified URL? I want to implement a validation check in my method, and if it fails, I need to stop this button from performing any action. Any suggestions or assistance would be highly apprec ...

Duplicate text content from a mirrored textarea and save to clipboard

I came across some code snippets here that are perfect for a tool I'm currently developing. The codes help in copying the value of the previous textarea to the clipboard, but it doesn't work as expected when dealing with cloned textareas. Any sug ...

The functionality of nested routing is not operating properly in react-router

I'm currently struggling to get my CollectionPage to render and match the URL correctly within my nested Route in React. Unfortunately, it doesn't seem to be working as expected! Here's a piece of code from my shop.component file that is be ...

The ReactJS redirect URL is constantly changing, yet the component fails to load

I recently started using reactjs and I encountered an issue with routing from an external js file. Here is the code in my navigation file, top-header.js import React from 'react'; import {BrowserRouter as Router, Link} from 'react-router-do ...

What is the process for setting %20 to represent a space in URL parameters?

I am currently working on developing an android application that involves sending data to the server side using GPRS and SMS (via an SMS gateway). The challenge I am facing is with formatting the data before sending it to the SMS gateway. The format provid ...

Ways to adjust text color after clicking on an element

Just a heads up, I didn't write all of the web-page code so I'm not exactly sure what pdiv is. But I want to see if I can fix this small issue [making text color change when clicked on to show which section you're reading]. This particular ...

Exploring nested optgroup functionality in React.js

Within my code, I am utilizing a nested optgroup: <select> <optgroup label="A"> <optgroup label="B"> <option>C</option> <option>D</option> <option>G</option> </optg ...

Discover the process for breaking down JSON data into separate stages using the Express API

My API architecture is causing a problem as I try to insert it into an array called items[]. https://i.stack.imgur.com/qe802.png The setup involves a simple API built on express + mongodb. The challenge lies in figuring out how to store data from the pos ...

Create a division that will remain visible on the screen and allow scrolling when a certain class is

Having some trouble with a fixed class div that is not continuing to scroll after the class is removed on scroll. I've attempted to fix this issue but the div keeps getting hidden instead of continuing to scroll. If anyone has any advice or can poin ...

javascript passing a window object as an argument to a function

In Slider function, I am passing a window object that does not contain the body element. Additionally, my code only functions correctly on mobile screens. While debugging the code below: console.log(windows.document); If (!mySlider) {console.log(windows. ...

Managing Server Crashes in Node.js

Is there a way to automatically update the database whenever my node.js server crashes or stops? Similar to how try{}catch(){}finally(){} works in JAVA. I am new to this. Does Node emit any events before shutting down so that I can run my function then? ...

A comprehensive guide to effectively formatting Recharts in React: addressing alignment and size management!

While attempting to style two graphs as floating cards, I am encountering difficulties in controlling the sizing and centering of the graphs. Specifically, I am having trouble with the pie chart in this example. To address this issue, I am passing paramete ...