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

Safari is unable to display the button text, while Chrome has no problem showing it

In Safari, the text of the button is not showing up properly. I am able to retrieve the text using jQuery in the console though. However, there seems to be an issue with recognizing the click event. <div class="btn-group btn-group-lg"> <button ...

Managing authentication sessions in React

I have been working on a two-part application that combines React, Express, and Apollo for GraphQL. To handle authentication, I have been studying guides and tutorials, and I have made progress by utilizing JWT tokens and the Context API in React: When a ...

Manipulate the label content of the last child using Javascript

On my BigCommerce website, I am trying to change the label text of a variable using a JavaScript function since the support team is unable to assist with this. Below is the code snippet that needs modification: <dd class="GiftCertificateThemeList" st ...

Creating an array with user-selected objects in IONIC 3

I've been attempting to separate the selected array provided by the user, but unfortunately, I'm having trouble isolating the individual elements. They are all just jumbled together. My goal is to organize it in a format similar to the image lin ...

Importing an external JSON file into a ChartJs chart

As a newcomer to using libraries for drawing charts in JavaScript, I recently started playing around with Chartjs. However, I'm having trouble figuring out how to use getJson or any other method to load my json object and update the labels and data. I ...

A guide to implementing div wrapping in HTML

I'm in the process of using flexbox on my website. I have 10 div elements that I want to wrap around each other closely without any gaps between them. My goal is to have "4" positioned to the right of "1", instead of creating a new row and moving dow ...

Trouble with $sce in Angular.js causing limitations on passing desired content into my directive

I've successfully developed a directive that animates a PNG Sequence. Everything functions perfectly when I manually input the image url, but when attempting to pass a dynamic url, I encounter an error related to $sce disallowing it. Below is the cod ...

Retrieve the element that was clicked by targeting its class name using JavaScript

Unfortunately, I couldn't create this example in JSFiddle as it's currently in read-only mode. My goal is to identify the specific element that was clicked based on a given class. var button = document.getElementsByClassName("mybutton"); button ...

Solving a riddle (most effective strategy)

Behold, a 3x3 number puzzle: 3 | 5 | 2 7 | 8 | 9 1 | 6 | 4 The ultimate goal: 1 | 2 | 3 4 | 5 | 6 7 | 8 | 9 The challenge is to only move adjacent "pieces" until reaching the solution. I attempted to solve this by computing the offset and implementing ...

Step-by-step guide on integrating Bulma page loader extension as a Vue component

Is there a way to integrate the Bulma-extension page-loader element as a Vue component in my project? I attempted to import page-loader.min.js and use it, but unfortunately, it didn't work as expected. <template> <div class="steps"> ...

Issues have been observed with the functionality of the Node.js EventEmitter when attempting to

Here's the issue: I have a class called save.js that inherits from EventEmitter. Here's how it looks: var util = require('util'); var EventEmitter = require('events').EventEmitter; var save = function(pdf){ var ...

The `appendTo` function in Ajax is used to swap out the current element

I have been working on sending form data to a Servlet using JQuery and then receiving the response from the same JQuery. Check out the code snippet below. <%-- Document : index Created on : Feb 23, 2015, 8:18:52 PM Author : Yohan --% ...

Update the image source through an AJAX call

I've experimented with various methods to update an image src using an AJAX request. The new URL is obtained through the AJAX call, and when inspecting the data in Developer Tools, the 'DATA' variable contains the correct URL. However, the i ...

Creating a visually appealing chart similar to Excel can be achieved using JavaScript with a whopping 64382 lines of JSON data. No need for Chart.js or any additional tools - simply rely on JavaScript, HTML, and CSS to

I have a project that is due in just a few hours and I need to create a detailed chart using a large set of 64382 lines of JSON data. My knowledge of javascript is limited, so I am struggling to come up with ideas on how to approach this task. While I have ...

The order of execution is not maintained for $.getJSON() calls within the $.each() loop

As I iterate through an HTML table, I am making a $.getJSON() request based on the data in each row. My goal is to retrieve the data from that $.getJSON call and update the corresponding row with it. Unfortunately, when I run my code, it seems to be execu ...

Redux saga will halt all other effects if one fails during execution

Having some trouble with yield all in saga effect, I've included a snippet of my code below function* fetchData(item) { try { const data = yield call(request, url); yield put(fetchDataSuccess(data)); } catch (error) { yield put(fetchDa ...

Issue with navigation links on HTML website not functioning as expected

I would like the dropdown menu items to be clickable. For example: Menu item: Services Sub items: - branding } These already have working links - marketing } However, when I try to replace '#' with a link for Services, it d ...

Using data-image as the source for Bootstrap Modal

I am currently working on an image gallery that utilizes the Paver jQuery plugin. The gallery is functional, but I am facing an issue where it displays the same image in the modal instead of showing the respective data-image for each image. My goal is to ...

Issue occurred while executing maildev - logger.info(`Shutdown signal received, beginning shutdown now...`)

After rebooting my machine, I encountered an error when running the maildev command in the terminal. Despite uninstalling and reinstalling the program, the issue persists. Below is the complete error message. Appreciate any help in solving this problem. ...

steps for including a JS file into Next.js pages

Is it possible to directly import the bootstrap.bundle.js file from the node_modules/bootstrap directory? import "bootstrap/dist/css/bootstrap.rtl.min.css"; function MyApp({ Component, pageProps }) { return ( <> <Script src="node_m ...