How come this 2-dimensional array is adding elements unexpectedly?

I just realized my error where the tempRndNumber was being reset in the inner loop. Although, I am still encountering an issue where "," characters are appearing in the array.

The goal is to create a 2D array that is populated only when a random number meets a specific condition (rnd >= 7). However, the current code is filling the 2D array with a combination of "," and the numbers that meet the criteria.

var tempAllRndNumbers = [];
    for (var i = 0; i < 10; i++) {
        for (var j = 0; j < 10; j++) {
            var tempRndNumber = [];
            var rndNumber = Math.floor(Math.random() * 10);
            if (rndNumber >= 7) {
                tempRndNumber.push(rndNumber);
            }
        }
        tempAllRndNumbers.push(tempRndNumber);
    }

My expectation was that tempAllRndNumbers would only contain numbers 7 and above. However, I am observing that the 2D array is filled with both "," and numbers 7 and above.

Answer №1

By resetting the tempRndNumber array to empty within the j loop, it will only store a number if the last iteration was >= 7. To resolve this, move the initialization of tempRndNumber outside of the innermost loop:

var allTempRndNumbers = [];
    for (var x = 0; x < 10; x++) {
        var tempRndNumber = [];
        for (var y = 0; y < 10; {
            var randomNum = Math.floor(Math.random() * 10);
            if (randomNum >= 7) {
                tempRndNumber.push(randomNum);
            }
        }
        allTempRndNumbers.push(tempRndNumber);
    }

Answer №2

It appears that a crucial check was omitted to verify the presence of values in the tempRndNumber array. Consequently, an empty array is being inadvertently pushed into the tempAllRndNumbers array, resulting in the presence of redundant ',' characters. This situation arises from indexes lacking corresponding values within the array.

Answer №3

It might be better to avoid resetting the tempRndNumber variable in every iteration of the inner loop. Consider the following code snippet:

var tempAllRndNumbers = [];
for (var i = 0; i < 10; i++) {
    var tempRndNumber = [];
    for (var j = 0; j < 10; j++) {
        var rndNumber = Math.floor(Math.random() * 10);
        if (rndNumber >= 7) {
            tempRndNumber.push(rndNumber);
        }
    }
    tempAllRndNumbers.push(tempRndNumber);
}

UPDATE: To achieve the desired output, make sure to loop through both arrays. Check out the solution here:

http://jsfiddle.net/jessikwa/1fbq0woo/

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

Instruction failed to produce HTML output

Currently facing a challenge with my code - I have a dynamically created span (via ng-repeat). <span my-size id="abc"></span> <span my-size id="def"></span> <span my-size id="ghi"></span> The goal is to extract the id ...

What is the regular expression that allows numbers between 1 and 24, including decimals?

Can anyone help me create a regex expression that only allows numbers between 1 and 24, with up to 2 decimal places? The numbers should range from 1 to 24, as well as include decimals like 1.00, 1.01, 1.02, all the way up to 24.99. ...

Automatically activate a button when it comes into view while scrolling

I am currently working in Joomla, which makes it challenging to create a fiddle, but here is the concept: My website displays a mosaic grid of 12 articles upon loading, along with a 'Load More' button. When this button is clicked, an additional ...

Accessing JSON data in Node.js can be accomplished using various methods. By leveraging

Currently, I am attempting to retrieve data from a JSON file using nodeJS However, upon running the code, I encounter the following error message: TypeError: Cannot read property 'postcode' of undefined. Any ideas on how to resolve this issue? ...

How can the horizontal scroll bar width be adjusted? Is it possible to create a custom

Within my div, I have implemented multiple cards that scroll horizontally using the CSS property: overflow-x: scroll; This setup results in a horizontal scrollbar appearing under the div, which serves its purpose. However, I would prefer a customized scr ...

Utilize the fitBounds feature from GoogleMaps in Vuejs for seamless integration

I've been working on getting the map boundaries to work properly, using a method in conjunction with my existing initMap and askGeolocation methods. Despite my best efforts, I can't seem to get the bounds functionality working so that the map zo ...

integrating a ui-bootstrap modal in a sidebar using angularjs

I recently utilized the modal example from https://angular-ui.github.io/bootstrap/ and everything worked perfectly. By using the code snippet below, I was able to successfully open the modal as shown in the example: $scope.open = function (size) { v ...

Having trouble getting Typescript code to function properly when using commonjs style require statements

I am completely new to Typescript, Node.js, and Express. Following the instructions outlined in this tutorial (https://www.digitalocean.com/community/tutorials/setting-up-a-node-project-with-typescript), I set up my project exactly as described there. The ...

When utilizing Reactjs, accessing an element by its id becomes challenging when the element is nested within a map() function

Currently, I am encountering an issue related to reactjs. In my scenario, I have a requirement to compare the height of the screen with a specific div to determine its maximum width. The challenge lies in the fact that the particular div I need to analyz ...

Error: The specified index is outside the bounds of the list (Python 3)

Encountering issues with handling a Python list. In my code, I need to store three variables (item name, id, location) in files. To achieve this, I have implemented a fairly complicated system. Each item name and its ID are saved in a .txt file based on th ...

Webshot is unable to retain any images

I attempted to utilize the Node package Webshot. The function is being executed, "OK" is printed to the console, but no files are saved to the specified folder. What could I be overlooking? if (Meteor.isServer) { var webshot = Meteor.npmRequire(&apos ...

Set a click listener on a button within Ext.window.MessageBox

Currently, I am dynamically generating a message box using Ext.window.MessageBox. var msgBox = Ext.create('Ext.window.MessageBox', { title: '', //message in window msg: 'message text', icon: ' ...

Encode the variable as JSON and nest it inside an array

I have been using json_encode to create an array through a foreach loop and I want to insert it into another static array. After storing the json_encoded array in a variable, I noticed that when I try to include this variable inside the static array, it do ...

Google Sheets Script encounters error: "Exceeded time limit for execution

I'm encountering difficulties when dealing with the "Exceeded maximum execution time" error in Google Sheets while running my script. Despite finding some solutions here, I couldn't get them to work with my script. Any assistance would be highly ...

Fixing the issue: "Tricky situation with JavaScript not working within Bootstrap 4's div tag while JS functions properly elsewhere"

Currently, I'm working on implementing a hide/show function for comments using JavaScript. Fortunately, I was able to find a helpful solution here (thanks to "PiggyPlex" for providing the solution on How can I hide/show a div when a button is clicked? ...

Utilizing JSON Data for Dynamically Displaying Database Objects on a Google Map

After carefully reviewing the information provided in the initial responses and working on implementation, I am updating this question. I am currently utilizing the Google Maps API to incorporate a map into my Ruby on Rails website. Within my markets mode ...

Step-by-step guide on populating input fields with JSON data for each row

As a beginner in Programming, I have been searching for an answer to the following problem on this site for days but haven't been able to figure it out yet. To explain briefly, there will be an input form where the user can define the number of rows ...

Feeling utterly bewildered by a project involving 2D arrays and generating random numbers

To fill a 2D array with random numbers ranging from 1 to 5, the numbers must be generated using the system time in nanoseconds. The process is a bit intricate. Assuming the array has 5 rows and 5 columns, it would be represented as: ... ... ... ... ... . ...

Having trouble getting AngularJS ngCloak to function properly?

My post category page is supposed to display a message if there are no posts. However, the HTML appears briefly when the page loads and then hides. I thought using ngCloak would solve this issue, but it doesn't seem to be working for me. Here's t ...

Developing an editor

Currently, I am delving into the concept of object inheritance in JavaScript through a practical exercise where I am creating an online editor similar to the one I am currently using. However, I find myself slightly confused as I aim to utilize data-* att ...