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

162
Vistas
Forming new 2d array by abstract some data in the other array

In a scenario where I have a 2d array like this:

[
  [0,1,4,2,2,5,5,0],
  [1,1,4,4,2,2,5,3],
  [1,6,6,6,7,7,3,3],
]

And I wish to abstract the same number into a single new 2d array like the one below: {either one}

[
  [0,1],
  [1,1],
  [1,0]
]

[
  [2,2,0],
  [0,2,2]
]

[
  [0,3],
  [3,3]
]

[
  [4,0],
  [4,4]
]

[
  [5,5],
  [0,5]
]

[
  [6,6,6]
]

How can I make this kind of logic in javascript? Basically, I need to have some sort of logic to generate either one multidimensional array on the above. Just imagine getting the same number from that 2d array.

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

0

// Initial Data
const arr = [
  [0, 1, 4, 2, 2, 5, 5, 0],
  [1, 1, 4, 4, 2, 2, 5, 3],
  [1, 6, 6, 6, 7, 7, 3, 3],
];

// Numbers you want to distribute to isolated arrays
const numbersForDistribute = [1, 2, 3, 4, 5, 6, 7];

const result = [];

for (let n of numbersForDistribute) {

  // find range within initial array for each number 
  // to determine size of result array for it 
  let minRowIndex = 999;
  let maxRowIndex = 0;

  let minColumnIndex = 999;
  let maxColumnIndex = 0;

  for (let i in arr) {
    const row = arr[i];

    for (let j in row) {
      const currentElement = row[j];

      if (row[j] === n) {
        if (i < minRowIndex) {
          minRowIndex = i;
        }

        if (i > maxRowIndex) {
          maxRowIndex = i;
        }

        if (j < minColumnIndex) {
          minColumnIndex = j;
        }

        if (j > maxColumnIndex) {
          maxColumnIndex = j;
        }
      }
    }
  }

  const resultForN = [];

  // build result array of specific size for each number 
  for (let i = minRowIndex; i <= maxRowIndex; i++) {
    resultForN.push([]);
    for (let j = minColumnIndex; j <= maxColumnIndex; j++) {
      resultForN[resultForN.length - 1].push(arr[i][j] === n ? n : 0);
    }
  }

  result.push(resultForN);
}

console.log(result);
.as-console-wrapper {max-height: 100% !important;top: 0;}
.as-console-row::after {display: none !important;}

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