An effective method for appending data to a multidimensional array in Google script

Is there a way to expand a multidimensional array of unknown size without relying on a Google Sheets spreadsheet to manage the data? I've searched everywhere but can't find an example for a 3-dimensional array.

Here's the challenge I'm facing:

var aDirTree=[];    
aDirTree[0][0][0]="myName1";
aDirTree[0][0][1]="myURL1";
aDirTree[1][0][0]="myName2";
aDirTree[1][0][1]="myURL2";
//Certain elements are being skipped
aDirTree[2][5][0]="myName3";
aDirTree[2][5][1]="myURL3";

Is there a way to handle the skipped values as null? I have a hunch that a push method might help solve this.

Answer №1

When taking a more relaxed approach, arrays can be used as keys (although they are converted to strings):

var o = {}
o[[1,2,3]]='a'
o['4,5,6']='b'

console.log(o)           // { "1,2,3": "a", "4,5,6": "b" }
console.log(o[[0,0,0]])  // undefined

Proxy(not available in IE) can provide another alternative, but it generates extra values:

var handler = { get: (a, i) => i in a ? a[i] : a[i] = new Proxy([], handler) }

var a = new Proxy([], handler)

a[1][2][3]='a'
a[4][5][6]='b'

console.log(a)           // [[],[[],[],[[],[],[],"a"]],[],[],[[],[],[],[],[],[[],[],[],[],[],[],"b"]]]
console.log(a[0][0][0])  // []

Finally, the most practical solution:

function set(a, x, y, z, v) { ((a = a[x] || (a[x] = []))[y] || (a[y] = []))[z] = v }
function get(a, x, y, z, v) { return (a = a[x]) && (a = a[y]) && z in a ? a[z] : v }

var a = []
set(a,1,2,3,'a')
set(a,4,5,6,'b')

console.log( get(a,0,0,0) )            // undefined
console.log( get(a,0,0,0,'default') )  // "default"
console.log( a )                       // [,[,,[,,,"a"]],,,[,,,,,[,,,,,,"b"]]]


Bonus: a combination of all 3 methods, although not very efficient due to key conversions to strings:

var a = [], p = new Proxy(a, { set: (a, k, v) => 
  ([x,y,z] = k.split(','), ((a = a[x] || (a[x] = []))[y] || (a[y] = []))[z] = v) })

p[[1,2,3]] = 'a'
p[[4,5,6]] = 'b'

console.log( a[[0,0,0]] )  // undefined
console.log( a )           // [,[,,[,,,"a"]],,,[,,,,,[,,,,,,"b"]]]

Answer №2

function addNodeToTree(tree, first, second, third, value)
{
    tree[first]                || (tree[first]                = []);
    tree[first][second]        || (tree[first][second]        = []);
    tree[first][second][third] || (tree[first][second][third] = []);

    tree[first][second][third] = value;
}
var directoryTree = [];
addNodeToTree(directoryTree, 1, 55, 3, "someContent");

To achieve arbitrary depth, you can use recursion:

function addNodeToTree(tree, position, value)
{
    var insertAt = position.shift();
    tree[insertAt] || (tree[insertAt] = []);
    if (position.length === 0)
    {
        tree[insertAt] = value;
        return;
    }
    addNodeToTree(tree[insertAt], position, value);
}
var directoryTree = [];
addNodeToTree(directoryTree, [1, 55, 3], "someContent");
console.log(directoryTree);

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

Using AngularJS to chain promises

After coming across some advice on AngularJS validation and promises, I am interested in creating a chain of confirmation dialogs to validate multiple steps at once. By making an API call based on user input, we can determine what steps require confirmati ...

The gradual disappearance and reappearance of a table row

I am struggling with making a row fade out when a specific select value is chosen (such as "termination"), and fade in when any other option is selected. The code works perfectly fine when the div ID is placed outside the table, but once I encapsulate it w ...

When the nesting in AngularJS ui-router becomes overwhelming

I've been in the process of refactoring a large application at work, and I've noticed significant similarities between different parts of the app that make me think nesting routes could be beneficial. However, as I continue to nest more and more, ...

Filter out elements with identical dates from a JSONArray

One of the tasks I have is to sort a JSONArray that contains JSONObject data. The structure of the JSON looks like this: [ { "id": 582, "isTransaction": false, "toDate": "2015-08-26 16:12:00.0", "fromDate": "2015-08-24 15:11:00.0", " ...

Do AngularJS applications function similarly to windows?

Do AngularJS apps behave like windows? And is it possible to add an event listener to them? I am currently working on a proof of concept to see if an Angular app can communicate with a server without impacting the host. One potential solution I have thou ...

When invoking a native prototype method, consider extending or inheriting object prototypes for added functionality

Recently, I came across a discussion on Inheritance and the prototype chain where it mentioned: Avoiding bad practice: Extension of native prototypes One common mis-feature is extending Object.prototype or other built-in prototypes. This practice, known ...

Concealing a div depending on the price variation

I'm looking for a way to dynamically show or hide a div based on the price of selected variations in my online store. Let's take a product with options priced at £359 and £455 as an example. In addition, there is a finance plugin with a minim ...

Is it unnecessary to mention both JavaScript and AJAX together?

During a recent conversation I had, someone mentioned that it is inaccurate to state that since Ajax is JavaScript. The scenario was: "How can I perform an action on a webpage without requiring a page refresh?" My response: "Utilize JavaScript along wi ...

Using JavaScript to set a form via a parameter in the URL

Is there a way to dynamically change the SetForm based on a parameter in the URL, such as radio.php?land=form2? I tried doing it this way but it doesn't seem to work. However, when I do it manually via the menu, it works. This is my first time attemp ...

Bootstrap 4: Popper not found - ReferenceError in the script

After setting up Bootstrap 4 using Node and Gulp, I encountered an error when running the application: Uncaught ReferenceError: Popper is not defined So far, I've only utilized the Bootstrap grid system and have not delved into the Bootstrap JS fu ...

Enhance Your Browsing Experience with Ajax Chrome Extension

I tried sending the URL to a PHP file in a Chrome extension, but I'm having trouble getting a response. manifest.json { "name": "Get pages source", "version": "1.0", "manifest_version": 2, "description": "Get pages source from a popup", "b ...

Undefined is the value assigned to Javascript Dot Notation

When using dot notation to access objects with a '.', I am encountering an issue that I cannot seem to figure out. The success function in my jQuery $.ajax function looks like this: success: function(data){ console.log('data = ' + da ...

Tips for efficiently loading data into a vuex module only when it is required and addressing issues with async/await functionality

Is there a method to load all the data for a Vuex store once and only load it when necessary? I believe there is, but I am having trouble implementing it. I'm not sure if it's due to my misunderstanding of Vuex or Async/Await in Javascript promi ...

Steps to create an instance method that only accepts the name of another instance method

I am looking to enhance an object by adding a method that specifically accepts the name of another method within the object. How can I achieve this in a way that dynamically narrows down the accepted names of methods, without hardcoding them? Let's t ...

Having trouble converting a JSON array into a JavaScript array upon creation

I have encountered this question multiple times before and despite trying various solutions, I have not been able to find success. Summary: My goal is to retrieve the array from the classes.json file and then assign the data in the variable classes from d ...

What is the best way to transition an absolute positioned element from right to center?

When hovering over an overlay element, I want the <h3> tag to appear with a transition effect from right to center, similar to the example shown here. Could someone please assist me in achieving this? Thank you in advance. HTML <div class="row m ...

Tips for swapping out a new line character in JavaScript

Hello! I'm currently facing a challenge with some code. I have a function designed to replace specific HTML character values, such as tabs or new lines. However, it's not functioning as expected. var replaceHTMLCharacters = function(text){ tex ...

Utilizing the ng-if directive to choose the second element within an iteration of an ng-repeat loop

I am currently working on a project where I need to organize and group content by day. While the grouping function is working fine, I am facing an issue with treating the first two items in the loop differently from the rest. I have experimented with using ...

AngularJS function orderBy reverses the array instead of sorting it

I encountered an issue where, after clicking the 'order button', the table does not order as expected. Instead, it reverses all the td elements. For example, 'A', 'C', 'B' becomes 'B', 'C', "A". I ...

Is there a way to verify the presence of months in a column related to departments?

Is there a way to validate whether the current row aligns with the current column month and year? If not, can it be set to 0. Let's consider the current dataset. Presenting my resultData https://pastebin.com/GHY2azzF I want to verify if this data ...