Add a new element to a multi-level array

function addValue(array, value, dimension) {
  switch (dimension) {
    case 0:
      array.push(value);
      break;
    case 1:
      array[array.length-1].push(value);
      break;
    case 2:
      array[array.length-1][array[array.length-1].length-1].push(value);
      break;
    case 3:
      array[array.length-1][array[array.length-1].length-1][array[array[array.length-1].length-1].length-1].push(value);
      break;
  }
  return array;
}


addValue([0,1], 9, 0) // [0,1,9]
addValue([0,[1]], 9, 0) // [0,[1],9]
addValue([0,[1]], 9, 1) // [0,[1,9]]
addValue([1,[2,[3,[4]]]], 9, 3) // [1,[2,[3,[4,9]]]]
addValue([1,[2,[3],2,[4]]], 9, 2) // [1,[2,[3],2,[4,9]]]

This function is only suitable for dimensions ≤ 3 and can be improved in terms of readability. Is there a better way to achieve the same result?

UPDATE:
I have a recursive get function to retrieve the last element in an array:

function getLast(array, dimension) {
  return dimension === 0 ? array[array.length-1] : getLast(array[array.length-1], dimension-1);
}

However, what I need now is an addValue function.

Answer №1

An iterative method will move through these steps:

Initial Step: Add to the 1st level, Just execute it.
Repetitive Step: Add to the nth level where n is greater than 0, Add to the n-1 level 

Throughout the process, it's important to verify that the input values for your function make sense.

LATEST UPDATE: Give this a shot:

 function addToDimension(array, value, dimension){
    if(dimension == 0){
       array.push( value );
    }else{
       addToDimension(array[array.length-1], value, dimension - 1);
    }

    return array;
  }

Note that this code has not undergone extensive testing, so proceed with caution.

Answer №2

Function.prototype.addition = function (num1, num2) {
  if (num2 > 0) {
    this[this.length - 1].addition(num1, num2 - 1);
  } else {
    this.push(num1);
  }

  return this;
}

then

a = [0,[1,2]]; a.addition(9, 0) // [0,[1,2],9]
a = [0,[1,2]]; a.addition(9, 1) // [0,[1,2,9]]
a = [1,[2,[3,[4]]]]; a.addition(9, 3) // [1,[2,[3,[4,9]]]]
...

(tested under rhino)

Answer №3

Give this iterative approach a try:

function addToArray(array, data, depth) {
    var temp = array;
    while (depth > 0) {
        for (var index=temp.length; index>=0; --index) {
            if (temp[index] instanceof Array) {
                temp = temp[index];
                depth--;
                break;
            }
        }
        if (index < 0) {
            break;
        }
    }
    temp.push(data);
    return array;
}

Answer №4

Based on what I know, the practice is to always add new elements to the final array within nested arrays. If this is correct, explicitly defining a dimension may be unnecessary.

findFinalArray = function(arr) {
  var lastElement = arr[arr.length - 1];
  return lastElement.push ? findFinalArray(lastElement) : arr;

}

exampleArray = [1, 2, [3, [4, 5]]]
findFinalArray(exampleArray).push(9)
console.log(exampleArray) // [1, 2, [3, [4, 5, 9]]]

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

Retrieving a JSON element using its name within a subquery in a Node.js MySQL environment

I've been working on a project that involves NodeJS and Mysql for the backend. Everything was going smoothly until I encountered a small issue after adding a SUBQUERY. Below is the Mysql Query: var GetHistoryPayments = function(code){ var qu ...

Adjust the color according to the chosen route in a Vue component

I am looking to dynamically change the CSS color based on the route or a prop for a route. For example, if I navigate to the home page, I want the header to be red. If I visit the about page, I want the header to be green. I have attempted this using rout ...

The challenge of having to manually refresh the browser each time an update is made using a put request in

When the user enters a name and number and clicks the add button, the new person's information is automatically added to the database. If the name already exists, a prompt will ask, 'name is already in the phonebook, do you want to update it with ...

The value retrieved from Axios is not properly set by React's useState function

My current challenge involves sending a GET request to http://localhost:8080/api/RE/template/${pageId} in order to display template items associated with a specific page ID. Upon checking the console, the following is displayed. https://i.sstatic.net/YCwe ...

ng-table Filtering with dropdown selection

Hello, I am currently working on creating a Ng-table with a select dropdown menu for filtering the results. Here is where I am at so far. 1) How can I remove one of the pagination options that appear after applying the filter? I only want to keep one pagi ...

Prevent fixed element from scrolling beyond a specific point

I'm working on a fixed sidebar that needs to scroll along with the main content and stop at a specific point when scrolling down, and vice versa when scrolling up. I've created a script that calculates the window height, current scroll position ...

Only incorporate the Angular service into the controller when it is necessary

When attempting to incorporate lazy loading for angular services, controllers, directives, and filters, I discovered a way to achieve something similar using RequireJS. However, I am struggling to find a way to dynamically load a service into a controller ...

After the page has finished loading, I aim to have the modal window pop up after 10 seconds. Thank you to all!

$(document).ready(function() { var id = "#dialog"; //Calculate screen dimensions var maskHeight = $(document).height(); var maskWidth = $(window).width(); //Adjust mask to cover entire screen $('#mask').css({'wid ...

Vue.js: The Power of Manipulating Strings

Why is the filter method not working with this.userId, but it is working with the hard-coded value "admin"? How can I resolve this issue? computed: { UidMessages: function() { return this.Messages.filter(function(m) { return m ...

Guide on merging non-modular JavaScript files into a single file with webpack

I am trying to bundle a non-modular JS file that uses jQuery and registers a method on $.fn. This JS must be placed behind jQuery after bundling. Here is an example of the structure of this JS file: (function($){ $.fn.splitPane = ... }(JQuery) If y ...

"Node.js: The Importance of Rest for Optimal Performance

Imagine this situation: As part of my cron jobs, I am utilizing an external service that limits requests to every 3600 seconds. This service's API is similar to GetPersonForName=string. I have multiple people in my database and it's necessary to ...

Alteration in style reminiscent of Facebook's design

I am in need of a code snippet that will allow me to run a MySQL query and change a link upon the first click. I came across this code, but it only changes the text: <script type="text/javascript"> $(document).ready(function() { // hides the ...

"Every time you use Firebase storage, you can expect a

I am facing an issue with my Vue 3 application. I am trying to retrieve a link to a document from the repository, but all I keep getting is a promise instead of the actual link. Can someone help me understand why this is happening? async FetchData({ state, ...

Datatables.js columns mismatch issue

Currently, I am facing an issue while trying to implement a datatables functionality using datatables.js in my asp.net core NET 7.0 project. The error message that keeps popping up states that there is an incorrect number of columns in the table. I have se ...

Utilize JavaScript to redirect based on URL parameters with the presence of the "@ symbol"

I need help redirecting to a new page upon button click using a JS function. The URL needs to include an email address parameter. <form> <input type="email" id="mail" placeholder="ENTER YOUR EMAIL ADDRESS" requir ...

The September/October 2013 release of the Ajax Control Toolkit is causing conflicts with jQuery

After updating our project to utilize the latest October 2013 release of the Ajax Control Toolkit for the HTML editor extender and Ajax file uploader, we encountered unexpected issues. Our ASP.NET 4.0 project, which previously used C#, jQuery 1.9.0, jQuery ...

The Power of ReactJS Spread Syntax

Currently working with React. In the state, I have an array of objects. this.state = { team: [{ name:'Bob', number:23 }, { name:'Jim', number:43 }] } My issue arises when attempting to create a copy of the arr ...

Resolving TypeError: matchesSelector method is not recognized within React component

I am currently integrating masonry-layout from the official website to create a masonry grid within my component. However, I encountered an issue where clicking on a rendered element triggers the error message TypeError: matchesSelector is not a function. ...

How to fetch files using URL in JavaScript

I need a solution for automatically downloading multiple PDF files from Google Drive and Docs using their URLs with JavaScript code. I don't want to manually go to each link to download the files. Although I've researched various answers on Stac ...

Trigger an Alfresco update action by adding content through a link

My current setup involves utilizing Alfresco Community Edition 4.0.e. I have set up Inbound and update rules on a specific folder. During the rule invocation process, my Java script is executed followed by calling my webservice. However, I am encounterin ...