1

I have an array in Javascript named "Files". Any element of array can be also be an array of 1D and with no limit in no of nested arrays.

So my situation here is that my array is dynamic and any element can be add at anytime and sometime when i have to access an element when i have given index of that element of Files array in an another array for example var index = [0,1,3,5] then it means that i have to access Files[0][1][3][5] of this array.

My problem that index can also be var index = [0,1] and number of index parameters is not fixed. So how can i write a function in javascript so that function can return value of element of "Files" given that i will provide it that index variable.

1

2 Answers 2

2

Sounds like you need to loop through all indexes. Something like this wrapped in the function:

var Files = [[0, [1, 2, 3, [0,1,2,3,4,5,6]]]]; var index = [0, 1, 3, 5]; function getElement(arr, indexes) { var val = arr, parts = indexes; while (val[parts[0]]) { val = val[parts.shift()] } return parts.length == 0 ? val : null; } alert( getElement(Files, index) );

Above will modify index array, if you need to preserve it you can work with its copy in the function: parts = indexes.slice().

Sign up to request clarification or add additional context in comments.

2 Comments

You also did same work that is shortening of array but your code is complete with check for existence of that element or not. Kyle Booth answer already made my work but your answer gave me another way using while and shift() instead of for loop. Thanks !
Can you tell me if i were to update that element in main array that is Files. How can i do that.
1

I did it in Python, hope this helps you out:

Index = [2,1,0] Files = [[1,2,3],[[1,2],3], [[1,2,3,4,5],[[[1,2],[1,2,3,4,5]],[1,2,3]]]] new_array = [] for i in range(len(Index)): new_array = Files[Index[i]] Files = new_array print Files [[1, 2], [1, 2, 3, 4, 5]] 

What this essentially does is for each stage of the index array, reduces the dimension of the Files array until you've found the final element of Files. Not sure that makes sense, let me know if I need to clarify.

5 Comments

"I did it in Python" - Why?
Just not familiar with javascript syntax and I wanted to test it to ensure it produced the desired result.
Your logic made my work complete in next 2 min just after your post ! Thanks !
Can you tell me if i were to update that element in main array that is Files. How can i do that.
Files can be whatever you want it to be... Just change it as you require!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.