-3

If I have an array like so:

let arr = [
  [],
  [],
  [
    1, 2, ["a"]
  ]
]

I want to get an item from the array given an array of indices.

Here is an example:

let arr = [
  [],
  [],
  [
    1, 2, ["a"]
  ]
]

function findByIndex(arr, indices) {
  // code here
}

findByIndex(arr, [2, 2, 0])
// returns `arr[2][2][0]` which is "a"

How can I do this?

3 Answers3

1

You can call .reduce() on your indices array to grab each index from your incidences array while updating the acc to be the value at that index, eventually leading to your final value:

const arr = [ [], [], [ 1, 2, ["a"] ] ];

function findByIndex(arr, indices) {
  return indices.reduce((acc, i) => acc[i], arr);
}

console.log(findByIndex(arr, [2, 2, 0]));

If you want to go the recursive route, you can use destructuring to pull the first index out from your indices array as well as grab the remaining indices using ...rest. If there are no more indices to search (when rest.length is 0), then you can stop your search and return the current value at the current index. If there are more items to search (rest.length has items), then you can recursively call your findByIndex function with the current element at index i from your array (arr[i]) and the remaining indices (...rest):

let arr = [ [], [], [ 1, 2, ["a"] ] ];
function findByIndex(arr, [i, ...rest]) {
  return rest.length ? findByIndex(arr[i], rest) : arr[i];
}

console.log(findByIndex(arr, [2, 2, 0]));
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
0

You can create a recursive function and if indices length is 1 then return the corresponding element from the arr. Else get the first element from the arr using the element at the 0 index of indices. Then use shift to remove the used index and recall the same function with new values

let arr = [
  [],
  [],
  [
    1, 2, ["a"]
  ]
]

function findByIndex(arr, indices) {
  if (indices.length === 1) {
    return arr[indices[0]]
  } else {
    const newArr = arr[indices[0]];
    indices.shift();
    return findByIndex(newArr, indices)

  }
}

console.log(findByIndex(arr, [2, 2, 0]))
brk
  • 48,835
  • 10
  • 56
  • 78
0

Use Array.prototype.reduce() to walk along the chain of indices of the nested array (or object) that you supply as the second argument of the reduce call:

let arr = [[],[],[1,2,["a"]]];
let res=[2,2,0].reduce((a,c)=>
 a[c],arr);
console.log(res);
In each cycle of .reduce() you will get one level deeper until you reach the final value.
Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43