I have a nested array like shown below.
var arr1 = ['a', 'b', ['c', 'd'], ['e', 'f']];
Is there a way to use another, un-nested array as the key(s) for arr1
?
var arr1 = ['a', 'b', ['c', 'd'], ['e', 'f']];
var arr2 = [3, 0];
var arr3 = [4, 1];
console.log(arr1[arr2]); // should return 'c' like arr1[3][0]
console.log(arr1[arr3]); // instead of arr1[4][1]; should return 'f'
Is there a function that allows me to do this?
You can make your own function that implements this behavior like so:
function nested_access(arr1, arr2) {
let ret = arr1;
arr2.forEach((index) => {
ret = ret[index];
});
return ret;
}
const arr1 = ['a', 'b', ['c', 'd'], ['e', 'f']];
const arr2 = [2, 0];
const arr3 = [3, 1];
console.log(nested_access(arr1, arr2)); // should return 'c'
console.log(nested_access(arr1, arr3)); // should return 'f'