Creating a triangle number pattern in JavaScript with a loop

Hi there, I'm currently facing an issue. I am trying to generate a triangular number pattern like the one shown below:

Output:
1223334444333221
=22333444433322=
===3334444333===
======4444======

I attempted to write a program for this, however, the logic I implemented is not working as expected.

function challengeAttempt(level) {
  let len = null;
  let result = [];
  while (level > 0) {
    let arr = [];
    for (let i = 1; i < level; i++) {
      for (let repeat = 0; repeat <i; repeat++){
        arr.push(i)
      }   
    }
// convert arr.push value from array to string using join
//and add 1 and the copy value using reverse
    let str_level = arr.join("") + "4444" + arr.reverse().join("");
    if (len == null) {
      len = str_level.length;
    }
    //Add Strip
    while (str_level.length < len) {
      str_level = "-" + str_level + "-";
    }
    result.push(str_level);
    level--;
  }
  return result.join("\n");
}

console.log(challengeAttempt(4))

If anyone can assist me with finding a solution, I would greatly appreciate it. Thank you!

Answer №1

This unique approach utilizes a double nested method involving two map functions to iterate over arrays of rows (for row count) and columns (values to be displayed in each row).

const size = 4
const fill = '='
const rows = Array.from({length: size}, (_, i) => i + 1) // 1,2,3,4
const cols = rows.concat(rows.slice(0, -1).reverse())    // 1,2,3,4,3,2,1

const result = rows
  .map(r => cols
    .map(c => ((c >= r) ? c : fill).toString().repeat(c)
    ).join('')
  ).join('\n')

console.log(result)

Answer №2

Although there are more efficient methods available, I am posting this to demonstrate how it can be done with minimal modifications from the original code (simply changing - to = and adjusting the for loop variable).

function number4(level) {
  let length = null;
  let output = [];
  while (level > 0) {
    let array = [];
    for (let index = 5-level; index < 4; index++) {
      for (let repeatCount = 0; repeatCount < index; repeatCount++){
        array.push(index);
      }   
    }
    // convert array values to a string using join
    // concatenate with "4444" and the reversed copy of the array
    let stringLevel = array.join("") + "4444" + array.reverse().join("");
    if (length == null) {
      length = stringLevel.length;
    }
    // Add equal signs to match the length
    while (stringLevel.length < length) {
      stringLevel = "=" + stringLevel + "=";
    }
    output.push(stringLevel);
    level--;
  }
  return output.join("\n");
}

console.log(number4(4))

Answer №3

function generatePattern(level) {
  let value = level;
  let length = null;
  let patternArr = [];
  while (level >= 0) {
    let numArr = [];
    for (let i = 1; i <= value; i++) {
      if (value !== i) {
        for (let repeat = 0; repeat < i; repeat++) {
          if (value - level <= i) {
            numArr.push(i);
          }
        }
      }
    }
    // convert numArr values from array to string using join
    // and add 4444 in between and then reverse the array elements
    let str_pattern = numArr.join("") + "4444" + numArr.reverse().join("");
    if (length == null) {
      length = str_pattern.length;
    }
    // Add dashes to make all strings equal in length
    while (str_pattern.length < length) {
      str_pattern = "-" + str_pattern + "-";
    }
    patternArr.push(str_pattern);
    patternArr = [...new Set(patternArr)];
    level--;
  }
  return patternArr.join("\n");
}

console.log(generatePattern(4));

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

Similar to AngularJS, jQuery also provides a powerful tool for submitting forms

Recently, I've delved into the world of angularjs and have been truly amazed by its capabilities so far. One thing that took me by surprise was the lack of a simple solution for sending AJAX requests using the $http service. After hours of searching G ...

Verification of user input field

For this mini deposit app, I needed to implement validation for the input field to check for three different conditions: no blank entries, only numerical values, and no negative numbers. Despite having the functionality, my attempts at implementing validat ...

What is the best way to add data from an array to a DOM element in the same order it was retrieved from Firebase?

Utilizing Google Firebase Firestore for data storage and the Open Movie Database (OMD) in combination with Axios to retrieve movie information. I am currently developing a website that allows users to add movies to collections. On the collections page, al ...

Obtaining a value from an array in a controller

There is a function within the controller that includes an array. function retrieve_articles(){ $data['retrieved']=$this->article_model->get_article(); $this->load->view('initial',$data);} I am looking to extract the secti ...

Swapping JSON: A Quick Guide

When my Angular code loads, a list of buttons (button 1, button 2, button 3, etc.) is displayed. Upon clicking any button, the console shows J-SON with varying values. Two additional buttons are present on the page for moving up and down. My dilemma arise ...

Webpack configuration for asynchronous loading

I'm having trouble making this work. Can someone please assist? :) (According to the documentation, webpack is capable of handling Promises) Here is what works for me: var compiler = webpack(webpackConfig) However, when I try using a promise, I en ...

Organizing NodeJS modules in a way that mirrors Maven's groupId concept

I am making the switch to NodeJS after working extensively with Maven. In Maven, we are familiar with the groupId and artifactID, as well as the package name when starting a new project. However, in NodeJS, I only see a module name. The concept of groupI ...

Attempting to generate a chart displaying computed values ranging from an initial number to a final number, with increments defined by a specified value

I am currently facing an issue with a specific part of my larger program. The problem lies in generating a table of calculated values that start and end at initial and final values. Strangely, the code works perfectly fine when the increment value is set t ...

What is the best way to populate a Set with an array of diverse objects that all inherit from the base object contained within the

Is there a way to populate a Set<SomeObject> with an array (Object[]) containing objects that extend the object in the Set? I have an array of objects and I want to convert it into a set of objects that are extensions of the objects in the array. He ...

Sending data when button is clicked from Google Apps Script to sidebar

I have been attempting to pass a list that includes both the start cell and end cell of the active range. I want to then assign each value from this list to separate input fields. document.getElementById("btn-get-range").addEventListener('click&apo ...

Unable to trigger onSelect event on the datepicker component

Whenever a date is chosen, I need to trigger a javascript function. Here is the javascript code: $(document).ready(function(){ var date_input=$('input[name="date"]'); //our date input has the name "date" var container=$('.bootstrap- ...

Exploring the functionality of JSON within the jQuery each method

I'm currently struggling with my JavaScript skills and attempting to piece this project together using various tutorials. However, I can't seem to identify why it's not functioning properly. Could someone guide me on how to properly pass an ...

Can a pledge be honored at a precise moment?

I have implemented transitions on my web page. When clicked, everything fades out to an opacity of 0 over a duration of 1 second. Then, a new page is swapped in and everything fades back in to an opacity of 1 over another 1-second duration. The issue aris ...

Aligning Content in the Middle of a Bootstrap Column

Can anyone help me with centering the content of a bootstrap column vertically? I'm facing an issue when setting width: 100% and height: 100% for the overlay div. Any solutions? Here is an example image of what I am trying to achieve: Below is the ...

File not found: The specified file 'C:Self Project eact-shopper eact-shopperclientuildindex.html' does not exist

I followed the tutorial and startup code by Reed Barger exactly, but every time I try to run the server I encounter this error: Error: ENOENT: no such file or directory, stat 'C:\Self Project\react-shopper\react-shopper\client&bso ...

I don't understand why this error keeps popping up. It seems that there are several `InputBase` components nested within a

Issue: The error message indicates that there are multiple instances of the InputBase component within a FormControl, causing visual inconsistencies. Only one InputBase should be used. I have tried enclosing my forms within the FormControl, but the error ...

Guide to mocking the 'git-simple' branchLocal function using jest.mock

Utilizing the simple-git package, I have implemented the following function: import simpleGit from 'simple-git'; /** * The function returns the ticket Id if present in the branch name * @returns ticket Id */ export const getTicketIdFromBranch ...

Issue with content overlapping when hamburger icon is tapped on mobile device

When the hamburger menu is pressed on smaller screens, I want my navbar to cover the entire screen. To achieve this, I included the .push class in my code (see the jQuery and CSS) to trigger when the .navbar-toggle-icon is pushed. However, after implemen ...

The use of multiple Where clauses in a Firestore Firebase query is not functioning as expected when implemented in JavaScript code

https://i.stack.imgur.com/DdUGj.png db.collection('User_Info').where("User_Name", "==", "Sam").where("PASSWORD", "==", "c2FtMTIzQA==").get().then(snapshot => { if(snapshot.docs.length > 0 ){ debugger; alert("Login Successful."); ...

designing various containers and adjusting their divisions

I have a pop-up window that contains the code snippet below, defining a template within a "container": <form method="post" class="signin" action="#"> <div id='container'> <div> <div id="divFeeTitle"&g ...