Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

139
Vistas
Multidimensional Array Javascript with nested loop

For example i have a array like that

var myArray = [
[1,2,3],
[4,5,6],
[7,8,9,10],
[[11,12],[13,14,15]]];

    for (var i = 0;i < myArray.length;i++){
    for(var j = 0 ;j< myArray[i].length;j++){
        for(var k = 0;k< myArray[i][j].length;k++){
            console.log(myArray[i],[j][k]);

        }
    }
        
      
}

   

But output is only 11,12,13,14,15. And i wanna print all the values Could some one help to fix Thank you in advance

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

This fucntion works for any depth of multi dimensional array. Using Recursion

var myArray = [1,2,33,44, [1,2,3], [[11,12],[13,14,15]]];

var myArray1 = [1,2,33,44, [[11,12],[13,14,15]]];


var deepFlattenArray = function (array){
    var result = []; 
    
    array.forEach(function (element) {
      if (Array.isArray(element)) {
          result = result.concat(deepFlattenArray(element)); 
      } else {
          result.push(element);
      }
    });
    
    return result;
};

console.log(deepFlattenArray(myArray));
 // output = [ 1,  2, 33, 44,  1, 2,  3, 11, 12, 13, 14, 15]

console.log(deepFlattenArray(myArray1));
// output = [1,  2, 33, 44, 11, 12, 13, 14, 15 ]
about 4 years ago · Juan Pablo Isaza Denunciar

0

Use e.g. Array.prototype.flat(), .flat(2) flattens to the level of 2 arrays deep.

var myArray = [
[1,2,3],
[4,5,6],
[7,8,9,10],
[[11,12],[13,14,15]]];

console.log(myArray.flat(2));
   

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use recursive function first pass it the whole array then loop it and check if the element you are accessing is array or digit if its array call the same function again and only pass it this element otherwise if its digit just print it

This works even when you dont know how many nested arrays you have otherwise use MWO answer

var myArray = [
[1,2,3],
[4,5,6],
[7,8,9,10],
[[11,12],[13,14,15]]];

function printArray(arr){
  for(var i = 0; i < arr.length; i++){
    if(Array.isArray(arr[i])){
      printArray(arr[i]);
    }else{
      console.log(arr[i]);
    }
  }
}

printArray(myArray);

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda