VisualXZ
VisualXZ

Reputation: 213

Return an n*n nested array populated with null

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.

Upvotes: 2

Views: 1238

Answers (3)

Ele
Ele

Reputation: 33736

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

Upvotes: 1

Nenad Vracar
Nenad Vracar

Reputation: 122105

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

Upvotes: 4

Igor
Igor

Reputation: 15893

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

Upvotes: 3

Related Questions