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

AngularJS Service Implementing the Pub/Sub Design Pattern

I've been browsing for solutions to a problem and stumbled upon an answer provided by Mark Rajcok angular JS - communicate between non-dependend services However, I am struggling to fully grasp his explanation, particularly this part: angular.forEa ...

Switch between showing or hiding at least three divs

I'm currently using a simple script that toggles the visibility of two div elements: <script type='text/javascript'> $(window).load(function(){ function toggle_contents() { $('#page1').toggle(); ...

Tips on creating a persistent form element that remains fixed as you input data into an array contained in the

I am a student in my final quarter of school working on a project that involves utilizing JQuery to dynamically add form fields. To achieve this, I need to use arrays for the name field to collect information from potentially multiple identical fields. Add ...

Why isn't $.post functioning properly in any instance?

I've been experiencing issues with my $.post calls throughout my code. Despite not sending requests to different domains, everything is localhosted. My Mac OS X 10.8 automatically defined my localhost alias as ramon.local, and I'm trying to make ...

Clicking on a href link inside a scrollable div-container causes it to malfunction, causing the page to jump

I have a draggable div container that contains dynamically generated content. In order to display this container, I use the following code: $( function() { $( "#dialog-message" ).dialog({ modal: true, height: 400, buttons: { Fertig: functi ...

In angular.js, repeating elements must be unique and duplicates are not permitted

My view controller includes this code snippet for fetching data from an API server: $scope.recent_news_posts = localStorageService.get('recent_news_posts') || []; $http({method: 'GET', url: 'http://myapi.com/posts'} ...

Upon attempting to add a new component, an error was encountered: Uncaught SyntaxError: Unexpected token export

I have created a React test project and added modules to my package.json as follows: { "name": "untitled", "version": "0.1.0", "private": true, "devDependencies": { "babel-preset-node5": "^12.0.1", "react-scripts": "0.9.5" }, "depe ...

Exploring the benefits of integrating ES6 modules in Express server technology

Is it possible to utilize ES6 modules in my Express application without relying on babel or @std/esm? find an alternative method that doesn't involve transpiling or using esm? Once I have started working on app.js in Express, it seems challenging to ...

Having trouble with object initialization in a jQuery GET request?

Looking to create an HTML button using jQuery that, upon clicking the chart button, will retrieve values from specified text inputs. These values will then be used to construct a JSON object which will subsequently be included in a GET request. $(".chart" ...

Rails successfully processed the request with a 200 OK status code, however, the $.ajax() function is triggering the 'error' callback instead of the 'success' callback

In my controller, the ajax request is handled as shown below (simplified): def create ... @answer = Answer.new(video: video_file) if @answer.save render json: @answer.video.url else ... end end This is how I have defined my ajax function: $.aja ...

How can you set the Quill text editor to read-only mode in Vue after clicking a button?

I have a quill text editor that I want to customize the default setting to be readonly. When a button is clicked, this setting should toggle between true and false. Here is my component code: <template> <div ref="editor"></div> ...

PHP code for checking the existence of a record using a While Loop

My task is to generate a random number, then check if it already exists in a database table. If the number is not unique, I must keep generating new numbers until a unique one is found. Below is the code I am using: $con=mysqli_connect($host,$user,$pass, ...

javascript hide rows without data

I have a knack for tweaking existing code to suit my needs, but I'm not very proficient in writing my own from scratch. That being said, here's my current dilemma. My pool league uses a Google sheet to manage a variety of statistics, and with so ...

Typescript enhances React Native's Pressable component with a pressed property

I'm currently diving into the world of typescript with React, and I've encountered an issue where I can't utilize the pressed prop from Pressable in a React Native app while using typescript. To work around this, I am leveraging styled comp ...

JQuery animations not functioning as expected

I've been attempting to create a functionality where list items can scroll up and down upon clicking a link. Unfortunately, I haven't been able to achieve the desired outcome. UPDATE: Included a JSFiddle jQuery Code: $(document).ready(function ...

When using JSON.Stringify in a React App, it only displays the first item and the length of the object instead of all the other items

Working on a React App, I encountered an issue while trying to convert an array to JSON and send it to the server. My approach was like this: console.log(JSON.stringify(mainArray)) I anticipated seeing output like this during testing: "breakfast": { ...

Select a single option from the group to include in the array

I'm currently developing a new soccer betting application. My goal is to allow users to choose the result of a match - whether it's a win, loss, or draw - and then save that selection in a list of chosen bets. https://i.stack.imgur.com/hO3uV.png ...

Guide to incorporating JSON data into HTML through JavaScript

As I attempt to load data from a JSON file to .js and then to an HTML file, I am facing a challenge. While I can successfully load the JSON values into .js, I am unable to transfer the same values to HTML. Below is the code snippet - could anyone provide a ...

Vue select component not refreshing the selected option when the v-model value is updated

Trying to incorporate a select element into a Vue custom component using the v-model pattern outlined in the documentation. The issue at hand is encountering an error message for the custom select component: [Vue warn]: Avoid directly mutating a prop as i ...

Retrieve Files with Angular Framework

I'm looking to implement a file download or view button using Angular without making a call to the backend. The file is static and the same for all users, so I want to avoid unnecessary server requests. Many solutions involve using the "download" att ...