1

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!

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
  • _`.push(n * value)`_ — That’s not how [`push`](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/push) works; at least this doesn’t lead to the desired result. _`for (const n of arr)`_ — This iterates all zero times over the empty array with the entirely new variable `n`; see the [documentation on `for`–`of`](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for...of). – Sebastian Simon Nov 22 '22 at 06:39
  • You need `for .. n` loop, the array is empty, `for .. of` loop is never entered. – Teemu Nov 22 '22 at 06:39
  • 1
    See [Two-dimensional string array creation](/q/36707546/4642212), [How can I create a two dimensional array in JavaScript?](/q/966225/4642212), [`Array.from`](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from), and [`Array.prototype.fill`](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/fill) for inspiration. – Sebastian Simon Nov 22 '22 at 06:43
  • Thanks for the quick replies, I'm getting mixed up with my loops and methods here –  Nov 22 '22 at 06:44
  • @jessica-98 `Array(n).fill(Array(n).fill(value))` creates an array with the _same_ nested array at different indices. Try changing any one nested index. Every nested array will change. The correct solution is `Array.from({ length: n }, () => Array.from({ length: n }, () => value))`. `Array.from({ length: n }, () => Array.from({ length: n }).fill(value))` is also acceptable, as long as the `value` is immutable. – Sebastian Simon Nov 22 '22 at 07:07

1 Answers1

0

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]]
Dimava
  • 7,654
  • 1
  • 9
  • 24