0

Exercise : Write a function that when given a number >= 0, returns an Array of ascending length subarrays. The subarrays should be filled with 1s.

How it should work :

pyramid(0) => [ ]
pyramid(1) => [ [1] ]
pyramid(2) => [ [1], [1, 1] ]
pyramid(3) => [ [1], [1, 1], [1, 1, 1] ]

This is the solution that I found online:

function pyramid(n) {
  const res = [];
  for(let i = 0; i < n; i++){
    res.push([...Array(i+1)].fill(1))
  }
  return res;
}

The solution works pretty well, but I really can't understand this line of code :

res.push([...Array(i+1)].fill(1))

I know how the methods push and fill work, but what [...Array(i+1)] means?

Stefano
  • 37
  • 3
  • See [What does this symbol mean in JavaScript?](https://stackoverflow.com/q/9549780/4642212) and the documentation on MDN about [expressions and operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators). Use the [browser console (dev tools)](https://webmasters.stackexchange.com/q/8525) (hit `F12`) and experiment with different inputs to see their results. – Sebastian Simon Oct 13 '19 at 08:40
  • @CertainPerformance I just tried function from question and with `res.push(Array(i+1).fill(1))` and both give same result. – Egan Wolf Oct 13 '19 at 08:53

1 Answers1

0

In very professional terms this operation is known as deholing ;). It takes holed array and makes it a proper array. It's done because most array operations don't work on holed arrays. But fill is not one of them.

If you want to know everything about holes, check this: https://2ality.com/2015/09/holes-arrays-es6.html

marzelin
  • 7,822
  • 1
  • 18
  • 35