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

202
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 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