+ 1
Array with variable dimension as reference
Does anybody know in JavaScript how i can do something like this: var arr1 = [1, [37, [4, []], [5, [321, []], [90, [4, []], [1, []]]], [3, []]]; var arr2 = [1, 2, 1, 0]; var result = ?arr1[arr2[0]][arr2[1]][arr2[2]]];? ..but 'arr2.length' is variable. So my question is: How can i 'create' the term between the question marks? It's basically a file system. arr1 represents the folder tree. In arr2 is the Path. I could do a switch/case where i fill my ?term? according to the length of arr2: var result; switch(arr2.length) case 1{ result = arr1[arr2[0]]; break; } case 2{ result = arr1[arr2[0]][arr2[1]]; break; } case 3 ... I was hoping it could be solved more elegant and efficient.
7 Respuestas
+ 2
You could use Array methods forEach or reduce.
https://code.sololearn.com/ca0a23a229a8
+ 4
I really wish i can understand what is going on .Can you try to explain it in a more simplified way please!
+ 3
The one by ODLNT is great , and also helped me understand how to actually make good use of reduce or forEach .
Between i came up with something else , not really an efficient or good way to do it though .
var arr1 = [1, [37, [4, []], [5, [321, []], [90, [4, []], [1, []]]], [3, []]]];
var arr2 = [1, 2, 1, 0];
let getValue=function(arr1,arr2){
str=`arr1`;
for(let i=0;i<arr2.length;i++){
str+=`[arr2[${i}]]`;
}
console.log(Function('"use strict";return (' +str +')')());
}
getValue(arr1,arr2)
+ 2
Abhay Thank for the kind words , Andreas Schenk , you're welcome and I'm glad we were able to help.
Here is a reference I used to help gain a better understanding of forEach and reduce and javascript overall.
https://javascript.info/array-methods#iterate-foreach
https://javascript.info/array-methods#reduce-reduceright
+ 1
It's basically a file system. arr1 represents the folder tree. In arr2 is the Path. I could do a switch/case where i fill my ?term? according to the length of arr2:
var result;
switch(arr2.length)
case 1{
result = arr1[arr2[0]];
break;
}
case 2{
result = arr1[arr2[0]][arr2[1]];
break;
}
case 3 ...
I was hoping it could be solved more elegant and efficient.
+ 1
Great, thanks a lot.