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

270
Visualizações
access nested uncounted arrays in JavaScript

I have nested arrays those the user made. I want a JavaScript code to access for example "g" element in it

var nestedArrays = [
  [a,b,c,d],
  [e,f,[
    g,h
  ]]
];

in this example i can access "g" element using this code

var element = nestedarrays[2][1][1];

BUT if "g" is nested in 100 of arrays i have to write a lot of square brackets as it

var g = nestedArrays[2][3][1][?][?].....[?];

OR i don't know how much "g" is nested

IS there an easy code to get any element in the nested arrays with pure javascript or jquery ???

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

0

If you're just trying to find a particular element you could flatten the array and find it that way.

var nestedArrays = [
  ['a','b','c','d'],
  ['e','f',[
    'g','h'
  ]]
];

const g = nestedArrays.flat(Infinity).find(x => x === 'g');

console.log(g);

about 4 years ago · Juan Pablo Isaza Relatório

0

We all know that array are zero-based.

In your first Example to access 'g' You need to access:

  • the second position (index [1]) which is ['e','f',['g','h']]
  • then access the third position (index [2]) which is ['g','h']
  • finally the first position (index [0]) and you get 'g'.
var nestedArrays = [['a','b','c','d'],['e','f',['g','h']]];
let x = nestedArrays[1][2][0];
console.log(x); // g

So from that we can say that to access 'g'
We need to follow this road of indices [1,2,0]

var nestedArrays = [['a','b','c','d'],['e','f',['g','h']]];
let roadToG = [1,2,0];

for(let i = 0; i < roadToG.length; i++){
    nestedArrays = nestedArrays[roadToG[i]];
}
console.log(nestedArrays); // g

BUT if "g" is nested in 100 of arrays i have to write a lot of square brackets as it var g = nestedArrays[2][3][1][?][?].....[?];

In case we want to access 'g' dynamically without hard code the road of indices; We must loop recursively in array till we find 'g', in looping we keep track of road

function loopRecursively( arr, x ,roadToX = []){
    if(JSON.stringify(arr).indexOf(x) == -1) return null; //in edge case where there is no x in array; we just return null!
    for ( let i = 0; i < arr.length; i++ ) {
        if( arr[i] == x ){
            roadToX.push(i);
        } else if( Array.isArray( arr[i] ) && JSON.stringify(arr[i]).indexOf(x) != -1 ){
            roadToX.push(i);
            loopRecursively( arr[i] , x, roadToX);
        }
    }
    return roadToX;
}
let nestedArrays = [['a','b','c','d'],['e','f',['g','h']]];
console.log( loopRecursively( nestedArrays, 'g' ) ); // [1, 2, 0]
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