2

I'm very lost here. Given a number, n, I have to return an n*n nested array populated with the value null. If n is 3:

[
  [null, null, null],
  [null, null, null],
  [null, null, null]
]

I am so lost. I've got something like this:

function generateMatrix (n) {
  let item = 'null';
  let array1 = [];
  let solution = [];
  array1.push(item.repeat(n));
  solution.push(array1.repeat(n));
  return solution;  
  }

I know it isn't right, not only because it's not working, but also because it doesn't make sense and I don't know how to do it. Bear in mind I'm very very junior, just started learning JS.

I've seen other similar threads, but can't figure it out.

Thanks in advance.

VisualXZ
  • 213
  • 3
  • 17
  • 1
    So given *n* - you need to loop that many times. Inside each loop, you need to loop again – tymeJV Mar 26 '18 at 21:12
  • `null !== 'null'`! – Nina Scholz Mar 26 '18 at 21:13
  • 1
    You want to first be able to create a row of n `null` - there are various ways such as loops, or you can use `Array.fill` (which loops the array internally), in combination with `Array(n)` which creates an array of length n containing `undefined` but uses `.fill` to change them to `null`, as in the below answer, to output `[null, null, null]` (if n is 3) and then use this same pattern to create a row of rows. So you would fill an array with n `[null, null, null]` to get the matrix you described. – George Mar 26 '18 at 21:21

3 Answers3

4

You could do this with Array.from and Array.fill methods.

function matrix(n) {
  return Array.from(Array(n), () => Array(n).fill(null))
}

console.log(matrix(3))

You can use the same approach to create matrix with rows x columns dimensions.

function matrix(rows, cols) {
  return Array.from(Array(rows), () => Array(cols).fill(null))
}

console.log(matrix(2, 4))
console.log(matrix(3, 2))
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
3

function generateMatrix (n) {
  let result = [];
  for (var i = 0; i < n; i++) {
    result.push([]);
    for (var j = 0; j < n; j++) {
      result[i].push(null);
    }
  }
  return result;  
}
console.log(generateMatrix(3));
Igor
  • 15,833
  • 1
  • 27
  • 32
1

This is an alternative using the function Array.from and the function fill.

var rows = 3;
var cols = 3;

var matrix = Array.from({length: rows}, () => new Array(cols).fill(null))
console.log(JSON.stringify(matrix, null, 2));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Array.from

Array.from() lets you create Arrays from:

  • array-like objects (objects with a length property and indexed elements) or
  • iterable objects (objects where you can get its elements, such as Map and Set).
Community
  • 1
  • 1
Ele
  • 33,468
  • 7
  • 37
  • 75