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?
CodePudding user response:
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'
CodePudding user response:
Just a simple method with reduce to walk the tree. (I changed your example indexes since they were off)
const lookUp = (arr, indexes) =>
indexes.reduce(
(acc, index) => acc[index],
arr);
var arr1 = ['a', 'b', ['c', 'd'],
['e', 'f']
];
var arr2 = [2, 0];
var arr3 = [3, 1];
console.log(lookUp(arr1, arr2));
console.log(lookUp(arr1, arr3));
CodePudding user response:
You can find the value by iteratively accessing properties using an array of property accessors:
function findValue (obj, propertyAccessors) {
try {
let result = obj;
for (const key of propertyAccessors) result = result[key];
return result;
}
catch {
return undefined;
}
}
const arr1 = ['a', 'b', ['c', 'd'], ['e', 'f']];
const arr2 = [2, 0];
const arr3 = [3, 1];
console.log(findValue(arr1, arr2)); // "c"
console.log(findValue(arr1, arr3)); // "f"
console.log(findValue(arr1, [2, 2, 3])); // undefined
If you attempt to access a property which doesn't exist, the result will be undefined
. If you continue to attempt to access another property on undefined
, an exception will be thrown. By using try...catch
, you can catch such an error and return undefined
.
CodePudding user response:
Try this:
function getValue(arr, arrKeys)
{
return arrKeys.reduce(
(acum, current) => acum?.[current]
, arr
)
}
var arr1 = ['a', 'b', ['c', 'd'], ['e', 'f']];
var arr2 = [2, 0];
var arr3 = [3, 1];
console.log(getValue(arr1, arr2))
console.log(getValue(arr1, arr3))
CodePudding user response:
You can create an array method Array#getNested
as follows:
Array.prototype.getNested = function(index) {
let out = this;
index.forEach(i => out = out[i]);
return out;
}
const arr1 = ['a', 'b', ['c', 'd'], ['e', 'f'], ['g',['h',['i', 'j']]]];
const arr2 = [2, 0];
const arr3 = [3, 1];
const arr4 = [4, 1, 1, 0];
console.log( arr1.getNested(arr2) );
console.log( arr1.getNested(arr3) );
console.log( arr1.getNested(arr4) );