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

203
Vistas
Flattening 2D grid of 2D arrays into a single 2D array, in JavaScript (functionally?)

I have a 2D array (grid) of 2D arrays (chunks) for a game I'm developing:

const c1 = [[1, 2],
            [3, 4]]

const c2 = [[5, 6],
            [7, 8]]

const c3 = [[9, 0],
            [1, 2]]

const c4 = [[3, 4],
            [5, 6]]

const grid_of_chunks = [[c1, c2],
                        [c3, c4]];

and I want to reduce/flatten the grid_of_chunks to:

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

I've been able to implement a functional solution for this (in 2 lines of Clojure), but I'm struggling to wrap my head around translating it to functional JavaScript, and bridging the gap between the two language's map semantics (JS map only accepts one array, whereas Clojure's map accepts many collections...).

This is as far as I got:

function join_grid_of_chunks(gofc) {
    const joined_horiz = gofc.map(
        gofc_row => [].map.apply(gofc_row, [cs => [].concat.apply(cs)])
    );
    return [].concat.apply(joined_horiz);
}

Edit: Clojure solution (which works for uniformly-sized square chunks, in an arbitrarily sized square grid):

(defn join-grid-of-chunks [gofc]
  (let [joined (map #(apply map concat %) gofc)]
    (apply concat joined)))
over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Here's what I have:

const c1 = [[1, 2], [3, 4]];
const c2 = [[5, 6], [7, 8]];
const c3 = [[9, 0], [1, 2]];
const c4 = [[3, 4], [5, 6]];

const grid_of_chunks = [
  [c1, c2],
  [c3, c4]
];

function transform(input) {
  return input.flatMap(rows => {
    return rows.reduce((result, chunk) => {
      chunk.forEach((row, rowIndex) => {
        result[rowIndex] = result[rowIndex] || [];
        result[rowIndex].push(...row);
      });
      return result;
    }, []);
  });
}

console.log(transform(grid_of_chunks));

Should work for NxN chunks and MxM grid

over 4 years ago · Santiago Trujillo Denunciar

0

A more general solution using flatMap is to map over the indices from the first chunk of each grid row.

function joinGridOfChunks(grid) {
    return grid.flatMap(row => row[0].map((_, i) => row.flatMap(chunk => chunk[i])))
}

With a zip function (such as the one in lodash), you could write it slightly more elegantly as:

function zip(...arrays) {
    return arrays[0].map((_, i) => arrays.map(arr => arr[i]))
}
function joinChunks(chunks) { // Horizontally join an array of chunks e.g. [[[1,2],[3,4]], [[5,6],[7,8]]] --> [[1,2,5,6],[3,4,7,8]]
    return zip(...chunks).map(row => row.flat())
}
console.log(gridOfChunks.flatMap(joinChunks));

zip plus map seems to be close to Clojure's map with multiple collections. This should work for any shape 2d chunks in a 2d grid.

over 4 years ago · Santiago Trujillo 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