Array with variable dimension as reference | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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.

17th Feb 2021, 4:58 PM
Andreas Schenk
Andreas Schenk - avatar
7 Answers
+ 2
You could use Array methods forEach or reduce. https://code.sololearn.com/ca0a23a229a8
17th Feb 2021, 7:45 PM
ODLNT
ODLNT - avatar
+ 4
I really wish i can understand what is going on .Can you try to explain it in a more simplified way please!
17th Feb 2021, 5:08 PM
Abhay
Abhay - avatar
+ 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)
17th Feb 2021, 9:40 PM
Abhay
Abhay - avatar
+ 2
Thanks Abhay . That's totally the direction I was thinking about. But I like the solution from ODLNT . I'm going to learn more about reduce and the arrow function. Again thanks to you both!
17th Feb 2021, 10:29 PM
Andreas Schenk
Andreas Schenk - avatar
+ 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
18th Feb 2021, 2:30 AM
ODLNT
ODLNT - avatar
+ 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.
17th Feb 2021, 5:28 PM
Andreas Schenk
Andreas Schenk - avatar
+ 1
Great, thanks a lot.
18th Feb 2021, 2:59 AM
Andreas Schenk
Andreas Schenk - avatar