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

187
Views
Weird behavor of generated object with arrays

I am trying to create a generative object, filled with arrays (all 0).

//declaration of the data object
var data = {}

//initiate to fill data with keys and arrays
function init()
{
 var pos = Array.apply(null,Array(16)).map(Number.prototype.valueOf,0); //creates empty array filled with 0
 for(var i = 0; i < 16; i++) {
  data[i] = pos;
 }
}

init();

console.log(data);

This would give me a data filled with keys from 0 to 2 and each key has an array filled with 0;

{
  '0': [
    0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0,
    0, 0, 0, 0
  ],
  '1': [
    0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0,
    0, 0, 0, 0
  ],
  '2': [
    0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0,
    0, 0, 0, 0
  ]
}

Now, when I try to modify a specific array like this:

data[0][1] = 1;

then the result will print that all arrays in all keys have been modified...

{
  '0': [
    0, 1, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0,
    0, 0, 0, 0
  ],
  '1': [
    0, 1, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0,
    0, 0, 0, 0
  ],
  '2': [
    0, 1, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0,
    0, 0, 0, 0
  ]
}

This makes no sense to me because I wanted to modify only the first array with key 0... If I create the whole object manually, the change will work fine, but if I do it this way (generative), I get this strange bug. Any ideas?

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

0

It is because every key in data is referencing to the same array. Array is an object. When you assing object to some variable, or pass it as argument, you just pass it refference.

To make your code to work correctly as you like, you have to generate new array every time, you want to assign it to some key in data.

const data = {};

for (let i = 0; i < 16; i++) {
  data[i] = new Array(16).fill(0);
}
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!