0

I was trying to get an array with some arrays inside of it, and each of those inner arrays should contain ONE of the n powers of 2, not all.

let n = 5;
    let arr = Array(n + 1).fill([]);
    const transform = function (el, i) {
      el.push(2 ** i);
    };
    console.log(arr); // [Array(0), Array(0), Array(0), Array(0), Array(0), Array(0)]
    arr.map(transform);
    
    console.log(arr); //[Array(6), Array(6), Array(6), Array(6), Array(6), Array(6)]
    //was expecting //[[1], [2], [4], [8], [16], [32]]
Ele
  • 33,468
  • 7
  • 37
  • 75

3 Answers3

1

Fill is just setting every index with a reference to that array. It is not creating a new array in every index.

The easiest way to create an array and fill it with empty arrays is with Array.from

const n = 5;
const transform = (arr, index) => arr.push(2 ** index);
const myArray = Array.from({length: n}, () => []);
myArray.forEach(transform);
console.log(myArray);
epascarello
  • 204,599
  • 20
  • 195
  • 236
0

When using fill, they share the same instance. So changing one changes all the others. You need to use map after filling

new Array(6).fill(null).map(() => []).map(transform)
Andrew
  • 7,201
  • 5
  • 25
  • 34
  • Oh, thank you! Did not even know a thing about "Instance". So the `.map(() => [])` kinds of "unbind" them? – Afar Abdalla Jul 01 '22 at 19:35
  • No, not an unbinding. `map` will not use the same value repeatedly. They are independently created. `fill` just takes the same value and applies it to every index. – Andrew Jul 01 '22 at 19:36
0

It may be easier to use a traditional for loop to accomplish your end result. Using map and transform is a more roundabout way of doing the following:

let n = 5;
let arr = [];
for (let i = 0; i <= n; i++) {
  arr.push([2**i]);
}
console.log(arr);
Bik
  • 328
  • 3
  • 10