Adding new element to 2D array

I'm currently facing an issue while attempting to insert strings into a 2D array using Google Apps Script. The behavior I'm encountering is quite peculiar and I'm struggling to comprehend it fully. Below is a simplified version of the code that demonstrates the same behavior:

function arrayTest() {
  var mainArr, subArr, i, arrLoc;
  mainArr = [];
  subArr = [];
  for (i = 0; i < 5; i++) {
    mainArr.push(subArr);
  }
  for (i = 0; i < 10; i++) {
    arrLoc = Math.floor(Math.random() * 5);
    mainArr[arrLoc].push('test');
  }
  Logger.log(mainArr);
}

I anticipated that the string 'test' would be inserted into the array at the index generated by the Math functions. For example, if the generated numbers were 0, 2, 1, 4, 4, 3, 0, 2, 1, 0, my expected output would be:

[['test', 'test', 'test'], ['test', 'test'], ['test', 'test'], ['test'], ['test', 'test']]

However, the actual output differs significantly:

[['test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test'], 
 ['test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test'], 
 ['test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test'], 
 ['test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test'], 
 ['test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test']]

It appears that 'test' is being added to each position in mainArr in every iteration of the for loop, rather than exclusively to the array at the index specified by the Math function.

I'm wondering if I'm overlooking something obvious, like an incorrect operator, or if I have misunderstood the workings of arrays. Any assistance or advice would be greatly appreciated!

Thank you.

Answer №1

You're encountering this issue because you're consistently adding the same array to the main array.

function arrayTest() {
  var mainArr, subArr, i, arrLoc;
  mainArr = [];
  subArr = []; // <-- This action creates an array and assigns it to the variable 'subArr'
  for (i = 0; i < 5; i++) {
    mainArr.push(subArr); // <-- The identical array is added to mainArr repeatedly
  }
  ...
}

However, I assume you intend to generate multiple arrays and push them into mainArr individually. To achieve this, your code should be adjusted as follows:

function arrayTest() {
  var mainArr, subArr, i, arrLoc;
  mainArr = [];
  for (i = 0; i < 5; i++) {
    subArr = []; // <-- This step creates a fresh array and assigns it to 'subArr'
    mainArr.push(subArr); // <-- The newly generated array is then added to 'mainArr'
  }
  ...
}

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

What is preventing me from using memoization in the getServerSideProps of NextJS?

I'm currently using React along with NextJS to showcase a variety of products on a specific category page. While I am able to successfully fetch the products utilizing getServerSideProps, I am not fond of how it continuously requests the product cata ...

Clearing Arrays in React Native Using useState

I'm struggling with the following code which aims to create an animated polyline for a map. I came across some examples online, but they were using outdated methods and didn't include useEffect or useState. I can't seem to clear the polylin ...

How can Observables be designed to exhibit both synchronous and asynchronous behavior?

From: Understanding the Contrasts Between Promises and Observables In contrast, a Promise consistently operates asynchronously, while an Observable can function in synchronous or asynchronous manners. This presents the opportunity to manipulate code in ...

Include personalized headers to the 'request'

I have configured my express server to proxy my API using the following setup: // Proxy api calls app.use('/api', function (req, res) { let url = config.API_HOST + req.url req.pipe(request(url)).pipe(res) }) In this instance, confi ...

A guide on successfully transferring JSON Data to an Express REST API

Currently, I am in the process of developing a REST API with Node/Express and have a query regarding the setup of the API along with integrating a JSON file. As an illustration, the JSON data that I wish to reference consists of an ID number, model, and co ...

Double execution of the Angular customFilter function

My goal is to use a custom filter in Angular to filter an array. Essentially, I have a binding set up like this: {{ myData.winners | getWinnerString }}, which returns an array of items with a length ranging from 1 to 4. If the array consists of more than ...

The module located at "c:/Users//Desktop/iooioi/src/main/webapp/node_modules/rxjs/Rx" does not have a default export available

I am currently delving into the realm of RxJs. Even after installing rxjs in package.json, why am I still encountering an error that says [ts] Module '"c:/Users//Desktop/iooioi/src/main/webapp/node_modules/rxjs/Rx"' has no default export ...

What is the process for reversing the texture application direction on a CylinderGeometry object?

Is it possible to reverse the orientation of texture mapping on a CylinderGeometry object? var obj = new THREE.Mesh( new THREE.CylinderGeometry(20, 15, 1, 20), new THREE.MeshLambertMaterial({color: 0x000000}) //the material is later changed to the ...

What is the best way to find the index of the smallest value in an array using JavaScript?

I recently created this function that currently outputs -1. function sayHello() { let buildingLevelsArray = [11,10,10]; var smallestIndex = buildingLevelsArray.indexOf(Math.max(buildingLevelsArray)); console.log(smallestIndex); } sayHello() ...

Create a custom route variable in Node.js with Express framework

Is there a way to achieve this particular task using express.js? In my express.js application, I have set up a route like so: app.get('/hello', (req, res) => { // Code goes here }); This setup is functional, but I am curious if it is poss ...

Including a unicode escape sequence in a variable string value

I'm struggling to find the right way to include a unicode escape in a dynamic string value to display emojis in React. My database stores the hexcode for the emoji (1f44d) I have set up a styled-component with the necessary css for rendering an emoj ...

Click event for jQuery horizontal accordion

I'm attempting to create a simple horizontal accordion-style element. My setup includes three 'banner' divs and three 'area' divs. Ideally, when I click on a banner, the corresponding area should animate - expanding in width to au ...

Plugin for saving inline edits in CKEditor 4

After creating a plugin for ajax save, I found the documentation confusing when it comes to implementation. How can I make the button responsive and able to save content using AJAX with PHP? Currently, I am unable to retrieve the content. Directory: /plug ...

Convert the data received from jQuery $.parseJSON into HTML code

I am using $.parseJSON to retrieve data from a specific URL. The link I receive contains {"status":"ok", "message":'<form><input type="text" name="" value=""> </form>'} Now, I want to add the "message" part to my content. $. ...

The sort function in Reactjs does not trigger a re-render of the cards

After fetching data from a random profile API, I am trying to implement a feature where I can sort my profile cards by either age or last name with just a click of a button. Although I managed to get a sorted array displayed in the console log using the h ...

How can I show the number of items in my filtered data using AngularJS?

My data array holds objects in JSON format. var users = { 'New':{ {Name:'One'}, {Name:'Two'} }, 'Old':{ {Name:'Three'}, {Name:'Four'} } This piece of code is used to disp ...

Extract data from the HTML source code in JavaScript and transfer it to a personalized JavaScript variable within Google Tag Manager

Running an e-commerce website on Prestashop and facing an issue with data layer set up. Instead of a standard data layer, the platform generates a javascript variable called MBG for Enhanced E-Commerce implementation. <script type="text/javascript"> ...

Why does the AngularJS ngRepeat filter permanently remove null values?

Check out this JSFiddle demonstration I created to illustrate the problem: http://jsfiddle.net/s6Lj2/2/ Observe that in the dataset $scope.places = [{ name: 'Chicago', status: 'Active', analyst: 'Sam', recor ...

Is it possible to extract around 10 variables from a JavaScript code, then display them on a webpage after execution?

I have just completed writing a Javascript code with around 3,000 lines. This code contains over 60 variables, but there are a few specific variables that I would like to display on my main HTML page. These variables include: totalTime longitudinalAcceler ...

Fullcalendar Unable to Show JSON Events on Feed

It seems like a common issue, but I've been unable to find a solution yet. I'm currently testing Fullcalendar with Scheduler on my local server. I'm attempting to replace the static data feed that's an array with data fetched from a My ...