Hey, I'm looking for some help with this question:
/*
Define a function called 'makeGrid'.
'makeGrid' should take in a number 'n' and some primitive value.
'makeGrid' should create a grid (an array of arrays), with the dimensions of n.
Return the grid filled with the given value.
*/
And here are some tests:
actual = makeGrid(2, "x");
expected = [
["x", "x"],
["x", "x"],
];
actual = makeGrid(3, false);
expected = [
[false, false, false],
[false, false, false],
[false, false, false],
];
I realise this should be a simple solution but I'm kinda lost in the woods with it, tried lots of different solutions but feel like I'm going around in circles. As I understand it I need to initialise the result with an empty array, then fill it with value * n number of arrays.
function makeGrid(n, value) {
let result = []
result.push(value * n)
}
This comes back undefined, which I understand, but any further clarity would be much appreciated. Thanks for taking the time to be here!
CodePudding user response:
You could do this with 2 steps:
- create
n
rows - each row is filled with
n
times ofvalue
const makeGrid = (n, value) => {
return Array.from({ length: n }, _ => Array(n).fill(value))
}
console.log(makeGrid(2, "x"))
console.log(makeGrid(3, false))
Without Array.from
const makeGrid = (n, value) => {
const rows = []
for (let i = 0; i < n; i ) {
rows.push(Array(n).fill(value))
}
return rows
}
console.log(makeGrid(2, "x"))
console.log(makeGrid(3, false))
References