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