Create a grid with dimensions of a number

97 Views Asked by At

beginner question here but any help much appreciated. I'm trying to define a function makeGrid that takes in a number 'n' and a primitive value. It should create a grid with the dimensions of n, for example:

let actual = makeGrid(2, "x");
let expected = [
["x", "x"],
["x", "x"],
];

I know I have to push n number of the value into the array but I'm only getting an empty array [] returned.

function makeGrid(n, value) {
    const arr = [];

    for (const n of arr) {
        arr.push(n * value);
    }
    return arr;
}

I'm trying to solve the problem with a basic for... loop if possible, if I can't get my head around those I probably shouldn't be venturing off into methods and arrow syntax just yet. Thanks for taking the time to read this!

1

There are 1 best solutions below

0
On

I generally use this one

function map2d/* <T> */(
    columns /* : number */,
    rows /* : number */,
    value /* : (x: number, y: number) => T */
) /*: T[][] */ {
    return Array.from(
        { length: rows },
        (_, y) => Array.from(
            { length: columns },
            (_, x) => value(x, y)
        )
    )
}
let m = map2d(3, 2, (x, y) => x + 2 * y)
// > [[0, 1, 2], [2, 3, 4]]