Home > Software engineering >  Flattening 2D grid of 2D arrays into a single 2D array, in JavaScript (functionally?)
Flattening 2D grid of 2D arrays into a single 2D array, in JavaScript (functionally?)

Time:03-11

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

CodePudding user response:

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

CodePudding user response:

Use Array.flatMap

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

const result = grid_of_chunks.flatMap(([a, b]) => [a[0].concat(b[0]), a[1].concat(b[1])]);

console.log(JSON.stringify(result));

  • Related