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?