What is preventing my for loop from reaching the initial index in this visually distinct nested array pattern?

Struggling with rearranging letters in a W shape using arrays. My code seemed to go down instead of reaching level 0.

Code snippet:

const row = totalLevel =>{
    let array = []
    for(let i =0;i<totalLevel;i++){
        array.push([])
    }
    return array
  }
  const inside = (str,rows) =>{
    let rowLevel = row(rows)
    // console.log(rowLevel)
    let level = 0
    for(let i =0;i<str.length;i++){
      rowLevel[level].push(str[i])
      if(level<rows-1){
        level++
      }
      else if(level === rows-1){
        level--
      }

    }
    console.log(rowLevel)
    let result =''
    for(let i =0;i<rowLevel.length;i++){
      result+= `Level ${i}: ${rowLevel[i]} \n`
    }
  return result
}
Driver code:
console.log(inside('DARWINFOX', 3))

//   Illustration : 
// D             I              X
//     A    W     N     O
//         R         F

//   expected result : DIXAWNORF
//   Final result will be: 
//   Level 1 : D, I, X
//   Level 2 : A, W, N, O
//   Level 3 : R, F

Answer №1

If the level is less than the total number of rows minus 1
, it will become true again once you move beyond level 2. The aim is to update the direction only when your level reaches either the upper or lower limit, depending on the current direction.

Modify the inside function’s for loop section as follows:

const inside = (str, rows) => {
  let rowLevel = createRow(rows),
    level = 0,
    direction = 1;

  for (let i = 0; i < str.length; i++) {
    rowLevel[level].push(str[i]);

    if ((level <= 0 && direction < 0) || (level >= rows - 1 && direction > 0)) {
      // Switch direction when reaching a boundary in the specified direction
      direction = -direction; // Reverse direction
    }

    level += direction; // Update level based on the current direction
  }

  // further implementation details go here…
}

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

After mapping the elements of the array twice, generate a new array

Two differently formatted bits of data may be received, each requiring different character stripping methods. The variable names are temporary and will be changed once the function is operational. const cut = flatten.map(obj => { return obj.file. ...

Exploring the method of retrieving object properties from JSON with BeautifulSoup and Python

from bs4 import BeautifulSoup import fake_useragent import requests ua = fake_useragent.UserAgent() import soupsieve as sv url = "https://search-maps.yandex.ru/v1/?text=%D0%9F%D0%BE%D1%87%D1%82%D0%B0%20%D0%A0%D0%BE%D1%81%D1%81%D0%B8%D0%B8,%20%D0%9A%D ...

At what point is the ajax call considered fully executed?

Whenever a client makes an AJAX call, they upload data to the server (HTTP request) and then receive data from the server (HTTP Response). Once the clients have received all the data, the AJAX request is considered successful, and the success callback func ...

Display arrays vertically within each column using PHP

I have an array with both rows and columns specified. My goal is to print each column as a list within a loop. $row = 3; $col = 4; $arr=[ '1' , '2' , '3' , '4', '5& ...

Each block in Svelte includes a unique shorthand attribute

I have a JSON variable that holds attributes in a specific structure: // This json variable defines the attributes for elements to be created let myElements = [ { attr1: "myAttr1", attr2: "myAttr2", }, { ...

Alter the app's entire background color in React.js with a button click

I am facing an issue with changing the background color of my entire React App when a button is clicked. Currently, I am able to change the color of the button itself but not the background. I have imported the App.css file into my project and I am looking ...

The search feature in AngularJS with filter appears to be malfunctioning

I've been attempting to use the angularjs filter method for searching, but it doesn't seem to be working correctly. Despite not seeing any errors in the console, the search results aren't showing up. Can someone lend a hand with this? Below ...

Struggling to incorporate infinite scroll feature into JSON script that is already functioning smoothly

After developing a phonegap application, I created a page called photos.html to fetch photos from my server using JSON. However, despite successfully retrieving all the photos stored in my MySQL database on the server with JSON, I struggled to integrate In ...

Is it possible to implement jQuery events on all elements belonging to a specific class

Hey there, I'm facing a little challenge with my code. Currently, I have a snippet that allows a user using iOS to drag around a <div> with the class .drag on the webpage. Everything works perfectly when there's only one instance of .drag, ...

Is there a way to send a Razor boolean variable to an Angular directive?

Within my cshtml file, I am working with a boolean variable. However, when attempting to pass this variable to my Angular directive, it is being received as "False" rather than "false". Even hardcoding it to be "false" in lowercase does not solve the issue ...

Avoid having logs displayed on the server end when utilizing console.log commands

Being new to JavaScript and Node.js, I am attempting to have my application output logs on the server side. getUser.onclick = function () { console.log('Server running at http://127.0.0.1:1337/'); var req = new XMLHttpRequest(); r ...

Having difficulties linking the front end and the back end despite diligently following the tutorial

Currently, I am experimenting with creating a real-time chat application by following a tutorial on YouTube from JavaScriptMastery. The tutorial link is here, and the GitHub repository is available at this link. Despite closely mimicking the code displayed ...

The CSS transition will only activate when coupled with a `setTimeout` function

After using JavaScript to adjust the opacity of an element from 0 to 1, I expected it to instantly disappear and then slowly fade back in. However, nothing seems to happen as anticipated. Interestingly, if I insert a setTimeout function before applying th ...

Encountering a top-level-await issue while utilizing the NextJS API

Currently, I am in the process of creating an API using NextJS and MongoDB. To start off, I have set up some basic code at the beginning of the API file: const { db } = await connectToDatabase(); const scheduled = db.collection('scheduled'); Fol ...

Is the indigo-pink color scheme fully implemented after installing @angular/material and scss using ng add command?

After running ng add @angular/material, we are prompted to choose a CSS framework and theme. I opted for indigo-pink and scss. Will the material components automatically inherit this theme, or do we need to take additional steps? When using normal CSS (wi ...

Incorporate a corner box feature to bring attention to the typed.js functionality

I have successfully integrated typed.js into my project and now I am looking to replicate the highlighted text with an excel-like box in one corner. I've managed to get the text typing out while also adding an SVG for the box in HTML, but I'm hav ...

Ways to verify user authentication for navigating Vue routes

Working on a Single Page Application with Vue front-end, Express, and Parse (parse-platform) for back-end. After authenticating the user, I store their info in a session variable req.session.user = result; before sending it back to the client using res.sta ...

The Console.log() function displays the current state and value of a promise object within the Q library

Whenever I attempt to print a promise object from Q, the result that I receive is as follows: var Q = require('q'); var defaultPromise = new Q(); console.log('defaultPromise', defaultPromise); defaultPromise { state: 'fulfilled& ...

Using AngularJS to bind objects with a checkbox

I am dealing with a nested list of objects that can go up to three levels deep. Each object contains another nested object, and this nesting can continue to multiple levels. I am interested in binding these objects directly to checkboxes so that when I che ...

Is there a way for me to retrieve the current value of a star rating when I click on it?

Looking for assistance with a ReactJS rating stars component that behaves oddly. The starting value is set to 5 stars, but each click on the stars seems to return the previous value rather than the current one. import React, {useState} from "react&quo ...