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.
-
You can use a loop: developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/…Felix Kling– Felix Kling2015年02月01日 05:59:42 +00:00Commented Feb 1, 2015 at 5:59
2 Answers 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().
2 Comments
while and shift() instead of for loop. Thanks !Files. How can i do that.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
Files. How can i do that.