-1

EDIT: The supposed "duplicate" question "Convert JavaScript string in dot notation into an object reference" is completely different than my question as explained using the example I provided. Aside the question itself, the provided arrays are in a completely different format than mine. The fact that the solution is similar doesn't mean that the question is a duplicate(!) you should know better than that -before downvoting the question (is this voting done by a webbot? it's too stupid for a human) -which doesn't make a difference for me anyway as I got the solution. It only damages the reputation of StackOverflow.

Example: I have array A and array B:

var A = [2, 4, 4, 2];

var B = 
    ["t1",
        "a",
            ["t2",
                "a",
                "b",
                ["t3",
                    "a",
                    "b"
                ],

                ["t4",
                    "a",
                    "b",
                    "c",
                    ["t5",
                        "a",
                        "b"      
                    ]
                ],    
            ],        

            ["t6",
                "a",
                "b",

                ["t7", 
                    "a",
                    "b"
                ]   
            ]  
    ]

and I want to use each elements of the unidimensional array A as keys in that exact sequence, in order to address the multidimensional array B as bellow:

var val = B[2][4][4][2].

How can I do that efficiently? I only found a solution for PHP, not javascript.

dllb
  • 59
  • 1
  • 7

1 Answers1

2

Use Array.reduce() on array A, and use array B as the initial value:

const A = [2, 4, 4, 2];

const B = ["t1",
  "a", ["t2",
    "a",
    "b", ["t3",
      "a",
      "b"
    ],

    ["t4",
      "a",
      "b",
      "c", ["t5",
        "a",
        "b"
      ]
    ],
  ],

  ["t6",
    "a",
    "b",

    ["t7",
      "a",
      "b"
    ]
  ]
]

const result = A.reduce((r, c) => r[c], B)

console.log(result)
Ori Drori
  • 183,571
  • 29
  • 224
  • 209