Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

168
Visualizações
Get value from nested array

i have an array that represents position inside nested array

const level = [2,1,0];

and nested array

const array = [

    [1,2,3,4],
    [22,33,444],
    [[7],[8],[9]]
    ];

i want to get element which position is represented in a level array, manually i would get it this way:

array[2][1][0]

but i need to write a function that itterates over level array which can be any length and returns element from this position, i've tried to use es6 reduce for this purpose but didn't succed can some1 help me with this issue, what am i doing wrong?

level.reduce((prev,curr) => {
  return prev[curr];
}, level[0]);

desired result: for level = [0,0] get value 1 for level = [2,1,0] get value 8

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can do that by using destructuring assignment and recursion:

const level = [2, 1, 0];

const array = [
  [1, 2, 3, 4],
  [22, 33, 444],
  [[7], [8], [9]],
];

const find = ([index, ...rest], { [index]: value }) =>
  rest.length ? find(rest, value) : value;

const result = find(level, array);

console.log(result);

Note that also works with composite trees with objects and arrays:

const level = ['prop', 1, 'otherProp', 1];

const tree = {
  prop: [
    {},
    { otherProp: [2, 4, 6] }
  ]
};

const find = ([index, ...rest], { [index]: value }) =>
  rest.length ? find(rest, value) : value;

const result = find(level, tree);

console.log(result);

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda