Coding in JavaScript

I need help creating a pyramid with odd numbers for edges. The desired output should look like this:
.......5
...3,4,3
1,2,3,2,1
(dots are simply for formatting)

So far, I have written the following code:

function p(n){
  let string = "";

for (let i = 1; i <= n; i++) {
 
  for (let j = 1; j <= n - i; j++) {
   string += " " ;
  }
  
  for (let k = 1; k <= 2*i-1; k++) {
    string += n-k +1;
  }
 string += "\n";
}
console.log(string);
  
}


p(5);

However, I'm unsure about how to proceed in order to achieve the intended result.

Answer №1

Here's a solution you can experiment with:

function createPyramid(number){
  let result = "";
  for (let i = 0; i <= number/2; i++) {
    let value = number - 2 * i
    for (let j = 0; j < Math.floor(number/2)*2 + 1; j++) {
      if(j < Math.floor(number/2) - i) {
        result += " ";
      }
      if( j >= Math.floor(number/2) - i && j <= Math.floor(number/2) + i) {
        result += value;
        j < Math.floor(number/2) ? value++ : value--
      }
      if(j > Math.floor(number/2) + i ) {
        result += " ";
      }
    }
    result += "\n";
  }
  console.log(result);
}

createPyramid(7);

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

Getting the value of a lookup in an alert or console within a Material table in React

I am currently integrating a material table into my project and I have encountered an issue. Instead of getting the name of a city, I am receiving numbers like 63 or 32 in alerts or console logs. For reference, here is the link to the CodeSandbox: https:/ ...

Alter the style type of a Next.js element dynamically

I am currently working on dynamically changing the color of an element based on the result of a function //Sample function if ("123".includes("5")) { color = "boldOrange" } else { let color = "boldGreen" } Within my CSS, I have two clas ...

Issue with scrollTop not functioning when using onclick on an <a> tag within a div

After various attempts and research online, I am still experiencing erratic scrolling behavior with the scrollTop function. My goal is to scroll within a specific div when clicking on links. The content of my div: <div id="test" style="height:400px; o ...

"An error occurred while trying to make a GET request with Axios:

I have been studying request method aliases lately. axios.get(url[, config]) and I am experimenting with the following code: const axios = require('axios') let data = new Date() let timer = date.getTime() const config = { 'kc-api-key&ap ...

Retrieve all dynamically created select elements using jQuery

I am using jQuery to retrieve and send data via ajax. I have select elements that can be dynamically generated by the user based on their needs. When any of these selects are changed, I want to collect all their values for later use. Unfortunately, I enc ...

Fixing the "Parsing error: Parenthesized pattern" issue using vanilla JavaScript

I'm currently working on a project for a job training program using HTML and JavaScript. The online code editor allows me to execute my code and there is even an "evaluate" button that verifies it against different test cases. My code functions as exp ...

transferring information from my webpage to an iframe with the help of JavaScript

Is there a way to utilize Payment Gateway in PhoneGap even though it is not specifically designed for PhoneGap? One idea I have is to use javascript to pass data to another jsp page via an Iframe that can control the Payment Gateway. I only need to pass ...

Change the background color of the MUI ToggleButton that is currently selected

I need help figuring out how to change the background color of a selected toggle button. Currently, the buttons are functional but do not visually indicate when one is selected. I would like the first button (Btn 1) to have a default color, and if the us ...

I am struggling to comprehend the code for a PHP form that triggers a JS OnUpdate event, which then uses AJAX to retrieve data from MySQLi

I want to give a special thanks to Alon Alexander for providing the JS and AJAX code, even though I don't fully comprehend it. I am more comfortable using PHP/JS without jQuery, but I am struggling to make it function as intended. My current issue in ...

Can I create this chart in chart.js?

Can Chart.js be used to create a graph like the one in this image? https://i.sstatic.net/Ve7Vr.png ...

The bootstrap table did not meet my expectations as I had hoped

I am currently using Bootstrap to create a basic two-column table similar to the one on the Bootstrap website here: http://getbootstrap.com/css/#tables. To achieve this, I have implemented a javascript function to display the table as shown below: $(&bso ...

What is the procedure for invoking a function when the edit icon is clicked in an Angular application

My current Angular version: Angular CLI: 9.0.0-rc.7 I am currently using ag-grid in my project and I encountered an issue when trying to edit a record. I have a function assigned to the edit icon, but it is giving me an error. Error message: Uncaught Re ...

JavaScript is throwing an error when clicking on functions and managing the z-index property

I am experiencing difficulties with my website code. I have defined all the necessary functions and CSS, but I keep encountering errors such as "clicked is not defined," even though it is clearly present in the script. The goal of the code is to bring the ...

Utilizing absolute path in Typescript: A comprehensive guide

I am currently working on a project written in Typescript running on NodeJS. Within the project, I have been using relative paths to import modules, but as the project grows, this approach is becoming messy. Therefore, I am looking to convert these relativ ...

Tips for accessing a variable within the document.getElementById('c1').innerHTML function in an Ionic application

Using the line of code below in my HTML file, I am calling HTML and CSS data from my home.ts file: document.getElementById('c1').innerHTML = '<ol><li>html data</li></ol>'; But what I really want to achieve is t ...

Combine Angular variable in JavaScript function

I want to combine "proposal.id" in the initial parameter of the window.open function. Here is my current code snippet: <button ion-button color="light" onclick="window.open('https://mywebsite.com/offer?id={{ proposal.id }}', '_self' ...

Unexpected Behavior: AJAX Response Does Not Append Desired Class

I'm currently developing a social networking site where users can post and comment on each other's posts. Upon initial page load, only two comments are displayed for each post, with the rest being hidden. Clicking on the "Load more" button reveal ...

Is there a way to keep a JS script running even after navigating away in the Google Chrome console?

Assume there is a basic script available var x = 0; run(); function run() { console.log(x++); setTimeout(run, 1000); } If I input it into the Google Chrome console. How can I keep it running even after navigating to another page (continuously d ...

Determine the minimum and maximum width of jQuery UI resizable during the "resizestart" event

As a newcomer to Javascript, I am facing challenges navigating my way around. Currently, I am attempting to create a jQuery plugin that will facilitate resizing elements using the jQuery UI resizable plugin. My goal is to implement logic that dynamically ...

Is it necessary to convert an HTMLCollection or a Nodelist into an Array in order to create an array of nodes?

Here we go again with the beginner guy. I'm working on this exercise from a book called "Eloquent JavaScript". The goal is to create a function similar to "getElementByTagName". However, the first function below is not returning anything and the secon ...