Having trouble with properly writing to multidimensional arrays?

The issue I am encountering is clearly depicted in the simplified code snippet below.

During the execution of the TestArrays function, the goal is to write a single item to each location in the multidimensional array. However, upon examining the layers in the console, it appears that every item exists in every layer. I am puzzled by this discrepancy and despite having successfully tackled similar problems in other programming languages, I am at a loss here.

It is worth noting that the layers where nothing was written indeed remain empty as expected. However, any writing to one address results in the presence of the item in all layers. To demonstrate this, I intentionally refrained from writing to the second address.

function ArrayND(initVal) {
  /***********************************************************************************************
   * The following function was sourced from Stack Overflow:
   * https://stackoverflow.com/a/33362121
   * It is responsible for creating the initial structure of the arrays
   ***********************************************************************************************/
  var args = arguments;
  var dims = arguments.length - 1

  function ArrayCreate(cArr, dim) {
    if (dim < dims) {
      for (var i = 0; i < args[1 + dim]; i++) {
        if (dim == dims - 1) cArr[i] = initVal
        else cArr[i] = ArrayCreate([], dim + 1)
      }
      return cArr
    }
  }
  return ArrayCreate([], 0)
}

function TestArray() {
  let myArray = ArrayND("blank", 3, 8, 4, 1);
  let emptyArray = [];
  let innerArray;
  let count = 1;

  for (let outer = 1; outer <= 2; outer++) {
    for (let middle = 1; middle <= 7; middle++) {
      for (let inner = 1; inner <= 3; inner++) {
        if (count != 2) {
          myArray[outer][middle][inner].push(emptyArray);
          let innerArray = [count, "Data1", "Data2"];
          myArray[outer][middle][inner][1].push(innerArray);
        }
        count++;
      }
    }
  }
  for (let outer = 1; outer <= 2; outer++) {
    for (let middle = 1; middle <= 7; middle++) {
      for (let inner = 1; inner <= 3; inner++) {
        console.log("Data at location: ".outer, middle, inner, "conatains: ", myArray[outer][middle][inner]);
      }
    }
  }
}

TestArray();

Answer №1

It was @Barmar who provided a solution to the question in the previous discussion.

The issue stemmed from JavaScript treating the emptyArray as a single instance no matter where it was initialized within the inner loop.

By modifying the code to use .push([]), the problem was resolved. A comment was necessary to clarify why an empty array was inserted in that specific location instead of at the beginning of the function.

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

Issues with slow scrolling and sticky sidebar on websites with infinite scrolling feature

My webpage has a sidebar that is supposed to scroll down with the page. However, I am experiencing some lagging issues where the sidebar appears a few seconds after scrolling. Additionally, the sidebar keeps moving downwards, making the page longer and cau ...

PHP function to determine if an array is a subset of another array

Let's consider the following: $hold = array(1, 1, 4); // this will return true $allArr = array(1, 1, 3, 4, 5); $containsHold = count(array_intersect($hold, $allArr)) == count($hold); When $containsHold is true, it is correct. Now, let's look at ...

"Encountering an 'Unexpected string' error when trying to implement a

$('.star').mouseover(function (){ var starIndex = $(this).index()1; $(this).parent().css("background-position", "0 -" + (32 * starIndex) + "px"); }); $('.star-rating').mouseout(function (){ var originalResult = $(this).attr ...

Unique option preservation on customized HTML select menus - Maintain original selection

Currently, I am attempting to replicate a custom HTML select based on the example provided by W3 Schools. You can view the demo through this link: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_custom_select The issue I am encountering is that ...

Focused Filtering in DataGrid Pagination

Seeking to adjust the font size of numerical values (10, 25, and 50 as shown in the screenshot below) within rows per page selection within a pagination section of a DataGrid component. https://i.sstatic.net/PnIDa.png After inspecting each number, it was ...

Tap on the HTML5 video to exit the fullscreen mode

Objective I have successfully implemented a fullscreen video setup that triggers when a link is tapped on a mobile device. To maintain a clean aesthetic, I have hidden the HTML5 video controls using CSS. The desired functionality includes closing the full ...

Vuetify's Handy Helper Classes

Hey everyone, I'm working on a vuetify project and I need to convert inline styles to utility classes (if possible) font-size: 24px; font-weight :600 I checked the documentation and noticed that it only provides options for setting size and weight wi ...

Retrieving Axios error codes within an interceptor

How can error codes like ERR_CONNECTION_REFUSED (indicating the API server is down) and ERR_INTERNET_DISCONNECTED (indicating the local network is down) be accessed when using response interceptors with axios in client-side JavaScript, React, etc.? While ...

Reading a file with fs alters the visibility of a global array, rendering it inaccessible beyond its scope

There are two sections of code. The first one is called by the second to populate an array and write it into a file. async function timeSeries(obj) { data = [ { original_value: [] } ] //read file named as passed obj ...

The cursor seems to be playing a game of hopscotch every time I

In the text box, I've implemented a feature to prevent typing of a forbidden character: #. While this feature is successful in restricting the input of the forbidden character, there's an issue that arises when data is already filled in the text ...

How to Implement Double Click Functionality in VueJS

I am facing an issue with my table where the columns have varying widths. To implement sticky headers, I need to calculate the column widths accurately. Initially, I created a function that increases the column width when double-clicking on the header. Su ...

Incorporate new markers into Google maps without the need to constantly initialize the map

My current goal is to have the user input a latitude and longitude into a text box, and then display a marker on the map for that location without needing to reinitialize the map each time. To start, I have set up my map like this: <script type="text/ ...

Although AJAX $.post functions properly in the View, it seems to encounter issues when relocated to a separate .js file. Interestingly, all other JQuery functions work

I have recently delved into MVC, JQuery, and AJAX, and encountered a perplexing issue. After completing the initial development of a practice website, I dedicated time to enhance the interactivity using JQuery. Everything was functioning smoothly until I ...

Ways to update modal content upon clicking a button

I have a scenario where I need to display 2 modals (box1 and box2) in my code with box2 appearing on top of box1. Each modal has its own button, and I want to make sure that box1 appears first. Then, when the user clicks the button in box1, it transitions ...

Trigger the function when the keyboard event is deactivated

Is there a way to continuously run the top set interval whenever I lift my finger from the space key? When I try using the key up event, it only executes that function once. I'm not sure how to implement if/else logic when adding an event listener. se ...

Transferring Data from Python Script to Browser (with an xserver running on a Linux system)

Looking for suggestions on how to efficiently transfer data from a Python script to a web browser. The Python script, as well as the browser, are operating under an xServer environment in Linux (specifically Raspbian on Raspberry Pi). The script is respon ...

Tips on navigating through complex nested JSON structures with Retrofit

I am experiencing difficulty with managing nested JSON using Retrofit. I have some experience parsing simple JSON with Retrofit, but navigating through nested JSON structures is proving to be a challenge. Here is the JSON data that I am working with... ...

AngularJS filter date is returning a value of NaN-NaN-NaN

I'm facing an issue where the filter I developed is functioning properly on Chrome but not on Firefox. I am puzzled as to why this might be happening. myApp.filter('dateCustom', [ '$filter', function ($filter) { return funct ...

Swapping a value within an array and moving it to a new position

Consider this scenario: I am dealing with a list of arrays containing values like: let data = [ "10-45-23:45", "10-45-22:45", "10-45-20:45", "10-45-23:45", "10-45-23:59,00:00-04:59", "10-45-23:59, 0 ...

Why is AJAX failing to execute PHP file from JavaScript?

The Issue: Hello, I have confirmed that my PHP file is functioning properly. However, the AJAX code connected to my JavaScript function seems to be malfunctioning. Even though the function is triggered, nothing happens as expected. The Script: Check o ...