What is the most efficient way to store arrays created within for loops into an empty array located outside of the loop structure?

(I have looked at similar questions that were asked before, but I couldn't find a satisfactory answer... my apologies!)

Hey everyone,

I am currently using a nested for-loop which is resulting in new arrays being created.

Each time the inner loop executes, I intend to add the generated array into an empty pre-defined array. My goal is to have an array of arrays as the final output.

While testing by console-logging each array generated within the inner loop, all the expected arrays are indeed being createdđź‘Ť. However, strangely, when I attempt to use .push() to include each one in the empty array, I end up with an array filled with index numbers instead of an array of arrays (???) .

If anyone understood that explanation, please lend a hand!! Thanks a bunch!

const isColourful = num => {
  const arr = num.toString().split('');

  const blankArr = [];

  const arrayOfArraysMaker = arr => {
    for (let c = 0; c < arr.length; c++) {
      for (let i = 0; i < arr.length; i++) {
        if (i + c > 0) {
          x = i + c;
        } else {
          x = undefined;
        }

        const workingArr = blankArr.push(arr.slice(i, x));
        console.log(blankArr);
      }
    }
  };

  arrayOfArraysMaker(arr);

  return arr;
};

console.log(isColourful(2457));

This code snippet returns a list of numbers from 1 to 16, while I was actually expecting an array containing the following arrays:

[ '2', '4', '5', '7' ]
[]
[]
[]
[ '2' ]
[ '4' ]
[ '5' ]
[ '7' ]
[ '2', '4' ]
[ '4', '5' ]
[ '5', '7' ]
[ '7' ]
[ '2', '4', '5' ]
[ '4', '5', '7' ]
[ '5', '7' ]
[ '7' ]

Answer â„–1

Your code seems to be functional, however there may be some confusion in your understanding.

const workingArr = blankArr.push(arr.slice(i, x));

The line above may not be achieving what you intended.

It's important to note that the push method of an array returns the new length of the array (more information here)

If you are utilizing the return value of push, it will increment by one each time the method is called because the array grows longer with each addition.

In this case, it is advised not to use the return value of push() as it directly modifies the original array.

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

Tips for implementing linear-gradient text in Android applications developed with React Native without using Expo

How can I implement linear-gradient text in react native mobile apps without using Expo? I want to apply a linear-gradient to change the text color. Is it possible to achieve this effect? If yes, please provide guidance on how to do it. If not, how do po ...

How can you condense specific array elements into a single array, while grouping the remaining elements under a separate category?

I have an array with common names and different surnames. I want to consolidate all these names into one array and keep the surname arrays nested inside. Here is an example: Array ( [0] => Array ( [Name] => Rahul ...

Click on the element inside an iframe using JavaScript

Possible Duplicate: Is it possible to trigger a "click" event programmatically for a file input element using JavaScript? I came up with a solution to enable single-click upload by concealing the <form> within an <iframe> like this (I sim ...

Instructions on activating dark mode with the darkreader plugin on a Vue.js website

Is there a way to implement DarkMode in a Vue.js application? I attempted to integrate darkmode using this npm package, but I kept encountering the error message: DarkMode not defined. ...

What is the process for obtaining X through the use of createElement('img')?

Is there a way to retrieve the X position from the left of the tag created using document.createElement('img'); var block00 = document.createElement("img"); block00.src = "images/sep1.png"; If so, how can it be done: if (block00.getBoundingCli ...

Trimming Picture on User's Device

Currently, I am utilizing the jQuery ImgAreaSelect 0.9.10 plugin to crop images that are uploaded by users. The data input format being used is "multipart/form-data". Upon cropping an image with the plugin, it provides me with coordinates in pixels. Howev ...

Is it possible to utilize multiple databases with NestJS and TypeORM?

I've been struggling for the past two days trying to figure this out, but it seems like I'm just not grasping the concept here. My objective was to create a NestJS application (with TypeORM integrated) that could serve as a RestAPI for 2 or 3 of ...

What is the best way to incorporate styled components into my React application?

This question is a bit tricky to name and may seem overly broad, so I ask for forgiveness from the moderators. I'm diving into the world of styled components for the first time while attempting to integrate them into my React app. The code snippet bel ...

What is the process of incorporating events into a calendar using jQuery or JavaScript?

$(document).ready(function () { //initialize calendar $(".responsive-calendar").responsiveCalendar({ time: '2016-02', events: { "2016-03-30": {"number": 5, "url": "http://w3widgets.com/responsive-slider"}, "201 ...

Centering an image that is absolutely positioned within a container that is relatively positioned, horizontally

Looking to center an image that is positioned absolutely horizontally within a container that is relatively positioned. After attempting with CSS and not finding success, I ended up using Jquery. http://jsfiddle.net/CY6TP/ [This is my attempt using Jquery ...

Ways to adjust the position of a DIV based on its index value

I'm currently working on a unique project that involves creating a triangular grid using HTML and CSS. The challenge I am facing is offsetting each triangle in the grid to the left by increasing amounts so they fit seamlessly next to one another. Righ ...

What is the best way to include an array variable with language file data in a library or helper so it is accessible in every controller file in CodeIgniter?

I am looking for a way to eliminate the repetitive array variable containing language files in every controller class. I have this public variable loaded with identical data in each controller, and it's becoming cumbersome to manage. Is there a way I ...

How can Vue FullCalendar be configured dynamically?

I am trying to dynamically change some options in Vue FullCalendar, but the calendar is not applying them. You can check out my example here. The button at the bottom should set the maxTime option from 20:00 to 18:00. Is there a way to refresh the calen ...

Customizing the attribute of an HTML tag using EJS or jQuery

Within my express server, I am rendering a page with the following data: app.get('/people/:personID', function (req, res) { res.render("people/profile", {person: req.person }); }); Inside my profile.ejs file, I can display the data within an ...

Dynamic loading of tinymce in progress

When tinymce is loaded in the head and before dom, everything works fine. However, if I attempt to load the JavaScript with ajax using jquery.getScript(), it doesn't work. I initialize tinymce when the user clicks the content area, so the dom must be ...

The type of undefined cannot be assigned to the specified type

I am currently working on implementing a pie chart (donut series) in Angular. Below are my HTML, CSS, and TypeScript files. I am following this tutorial resource: Link to CodeSandBox - https://codesandbox.io/s/apx-donut-simple-8fnji?from-embed import ...

Extract particular XML element(s) and incorporate them into an HTML webpage

Just diving in for the first time. I hope you all can bear with me. This particular issue might have similarities with others, but from what I've gathered, this is a unique problem that I'm tackling. For your information, my expertise lies in de ...

Adding an onload event to a popup window using Javascript

I am attempting to add an onload event to a popup window in the following way: var newPopup = window.open(PARAMS...); newPopup.onload = function() {window.opener.unlockObj(id);} The goal is to disable the button that launches the popup window until all o ...

Node.js using Express: Modifying response data for specific route

I've searched through numerous resources but haven't been able to find a solution, so I'm reaching out for some assistance! :) I have developed a UI5 Application using Node.js with Express on the server-side. The data is retrieved from a SQ ...

Processing of JSON data and manipulation of string constants

Looking for help with using a string constant in JavaScript? MyString.START = 'start'; If you have a JSON object named input and want to access a property based on the value of MyString.START, the syntax would be input[MyString.START]. Does th ...