-2

var arr = [[],[],null,[[],[]],[[[]]]];
$( document ).ready(function() {
  
  
  
  addChild(arr, 'main');
  
  
  
});

function inscribe(numbers, value) {
    while(numbers.length>1){
      arr = arr[numbers.shift()];
    }

    arr[numbers.shift()] = value;
    
    addChild(arr, 'main');
    
  }
  
  function addChild(subarr, id) {
    var el = document.getElementById(id);
    var ul = document.createElement("ul");
    el.appendChild(ul);
    subarr.forEach(function(item, index){
      var node = document.createElement("div");
      var textnode = document.createTextNode(id + '-' + index);
      node.appendChild(textnode);
      node.id = id + '-' + index;
      ul.appendChild(node);
      if(item && item.length)
        addChild(item, node.id);
    })
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="main"> </div>

<button onclick="inscribe([3,1], [[]])">inscribe([3,1], [[]])</button>

Let's suppose I have a nD array which its values is dynamically changing. let arr = [[],[],[[],[]],null,[]];. I need a function which receives an array of numbers, and a value, to change that value of the main array.

/*
 * numbers: an array of integers which indicates which element of array should be set
 * value: the value that should be set
 */
inscribe(numbers, value) {
   // set value for desired position
}

For example if numbers are [x,y,z], it should change arr[x][y][z] = value. notice that we do not know the length of numbers array. Any suggestion for implementing the function?

6
  • loop over numbers. Use bracket notation, set value on last index. Commented Dec 2, 2019 at 16:32
  • can you explain more please? @epascarello Commented Dec 2, 2019 at 16:39
  • Same thing as this: stackoverflow.com/questions/15092912/… Commented Dec 2, 2019 at 16:42
  • I did the same thing, it doesn't work the array Commented Dec 2, 2019 at 16:52
  • It does too.... it is no different. You have the array split up already. The string uses split to make the array.... Commented Dec 2, 2019 at 16:53

1 Answer 1

1

You could use recursion to get/change the values;

function inscribe(arr, path, value){
   if(path.length == 1){
      arr[path[0]] = value;
   }else{
      var next = path.shift();
      inscribe(arr[next], path, value);
   }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.