Owthaman Rooben Owthaman Rooben - 2 months ago 17
Javascript Question

Accesing multidimensional array javascript

If the following is my array of question, how can I get the value in the position

[0][2][1]
by supplying the index values in an array eg:
answer = [0, 2, 1]
.



var question = [
[
['x', 'x', 'x'],
['x', 'x', 'x'],
['x', 'x', 'x']
],
[
['x', 'x', 'x'],
['x', 'x', 'x'],
['x', 'x', 'x']
],
[
['x', 'x', 'x'],
['x', 'x', 'x'],
['x', 'x', 'x']
]
];

var answer = [0,2,1];

question.get(answer); // Is there a way like this?




Is there way like question.get(answer) or question.get([0, 2, 1])?

Answer

There's a hard coded way:

question[answer[0]][answer[1]][answer[2]];

or for any length of a array or nested array:

  var question = [
      [
        ['x', 'x', 'x'],
        ['x', 'x', 'x'],
        ['x', 'x', 'x']
      ],
      [
        ['x', 'x', 'x'],
        ['x', 'x', 'x'],
        ['x', 'x', 'x']
      ],
      [
        ['x', 'x', 'x'],
        ['x', 'x', 'x'],
        ['x', 'x', 'x']
      ]
    ];

var answer = [0,2,1];

    var getanswer= function(answerinput,questioninput){
      var val = questioninput;
      answerinput.forEach(function(item){
        val = val[item];
      });
      return val;
    }


    console.log(getanswer(answer,question));