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

132
Vistas
How to create nested array of different length from a multidimensional array

I have an array that looks like this:

arr = [[1,2,3],
       [4,5,6],
       [7,8,9]]

I have initialized an empty array and I want put the diagonals of the arr inside the new array. So i've tried this:

arr = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
]
new_arr = [];
tail = arr.length - 1;
for (let i = 0; i < arr.length; i++) {
  for (let j = 0; j < arr[i].length; j++) {
    if (j == i) {
      new_arr.push(arr[i][j]);
    }
    if (j == tail) {
      new_arr.push(arr[i][j]);
      tail--;
    }
  }
}

console.log(new_arr)

The logic seems to work but I can't seem to get the structure right. What I want is to nest two arrays inside the new array like this:

[[1,5,9],[3,5,7]]

But what I get is one array with the right values unordered. How to get the expected output? Any help is appreciated. Thanks!

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

0

var arr = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];


var diagonal1 = [];
var diagonal2 = [];

for (var i = 0; i < arr.length; i++) {
  diagonal1.push(arr[i][i]);
  diagonal2.push(arr[i][arr.length - i - 1]);
}

var new_arr = [diagonal1, diagonal2];
console.log(new_arr)

about 4 years ago · Juan Pablo Isaza Denunciar

0

The following solution would work for you if the width and height of the number matrix is always equal.


const arr = [[1,2,3],
       [4,5,6],
       [7,8,9]];

const result = [[],[]];
arr.map((row,index) => {
  result[0].push(row[0+index]);
  result[1].push(row[row.length - index - 1]);
});


console.log(result); // [[1,5,9],[3,5,7]]
about 4 years ago · Juan Pablo Isaza Denunciar

0

You need to have 2 separate temporary arrays. And you don't need nested loops. You can optimize the code like this with a single loop if you understand the math.

arr = [[1,2,3],
       [4,5,6],
       [7,8,9]];
       
function findDiagonals(arr) {
  const diagonal_1 = [];
  const diagonal_2 = [];
  
  for( let i = 0; i < arr.length; i++ ) {
    diagonal_1.push(arr[i][i]);
    diagonal_2.push(arr[i][arr.length - (i+1)]);
  }
  
  return [diagonal_1, diagonal_2];
}

console.log(findDiagonals(arr));

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