2

I am trying to create a multi dimensional array programmatically. But when i push an object into the array it gets pushed into all indexes in the array. Why is this happening

Here's a simple demo

let postTest = new Array(4).fill([]);
postTest[0].push({key: 'value', anotherKey: 'value'});
console.log(postTest);
3
  • 1
    That's because you fill the array with the same reference. Commented Apr 7, 2020 at 14:09
  • @MoritzRoessler could you provide a link or explain in more detail please? Commented Apr 7, 2020 at 14:10
  • 2
    @Reece developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Apr 7, 2020 at 14:11

2 Answers 2

6

Use Array.from instead, Array.prototype.fill copies the reference of object on all places so any change at one place will reflect at all places

let postTest = Array.from({length: 4}, ()=> []);

postTest[0].push({ key: 'value',  anotherKey: 'value' });

console.log(postTest);

Sign up to request clarification or add additional context in comments.

Comments

2

As mentioned in the fill() method docs:

value
Value to fill the array with. (Note all elements in the array will be this exact value.)

You can fix this issue, by assigning the empty array to individual index using .map() so that there no reference issue like:

let postTest = new Array(4).fill().map(x=>[]);
postTest[0].push({key: 'value', anotherKey: 'value'});
console.log(postTest);

You can also, try:

let postTest = [...Array(4)].map(x=>[]);
postTest[0].push({key: 'value', anotherKey: 'value'});
console.log(postTest);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.