Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

176
Views
Why am I getting an array with six Array(6) instead of six Array(1)?

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

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

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)
about 4 years ago · Juan Pablo Isaza Report

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

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!