Index an array of arrays with an array of indexes in javascript
Given an array of arrays [of arrays ...] such as:
array[a][b][c][d][e]
And an array of indexes:
indexes = [ a, b, c, d, e ];
Is there an elegant way to index the array of arrays using the array of indexes?
The brute force method I am using is:
element = array[indexes[0]][indexes[1]][indexes[2]][indexes[3]][indexes[4]]
EDIT
To be clear, I would to be able to use an arbitrary array of indexes from 1 to n elements, where n is the depth of array nesting.
So given the above example of five-level nested array of arrays, and given an index array of:
indexes2 = [ a, b, c ];
I would expect to retrieve:
array[a][b][c]
Solution 1:
You can use Array.reduce()
to go through the indexes
and get the element you want.
// array[a][b][c][d][e]
var indexes = [ a, b, c, d, e ];
var element = indexes.reduce(function(prev, curr){
return prev[curr];
}, array);