Looking for a function that can extract a value from an array containing multiple arrays? Simply use getValueFromArray(array, [2, 4]) to get the 4th element of the 2d array within the main array.
Check out the code snippet below:
function getValueFromArray(arr, indexes){
var val,
currentIndex = indexes[0];
if(!arr[currentIndex] || arr[currentIndex] === '') return value = '';
indexes.splice(0, 1);
if(arr[currentIndex].length)
getValueFromArray(arr[currentIndex], indexes);
else {
val = arr[currentIndex];
return val;
}
}
var y = getValueFromArray([[1,2,3,4], [1,2,3,4]], [0, 2]); // should return 3
var x = getValueFromArray([[1,2,3,4], [1,2,3,4], [5,6,7,8]], [2, 3]); // should return 8
var z = getValueFromArray(
[
[[1,2,3,4], [1,2,3,4], [1,2,3,4]],
[[1,2,3,4], [1,2,3,4]]
],
[0, 1, 2]
); // should return 3
The function correctly returns the expected value when debugged directly. However, while trying to assign it to a variable, it shows undefined. This issue might be due to recursion. Any suggestions on fixing this?
Appreciate your help!