0

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]

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

1 Comment

That appears to do the job exactly, and is not likely a solution I would have stumbled onto on my own. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.