Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Notifications
Mark all as read
Q&A

Why does pushing to one array affect all the arrays in my two-dimensional array?

+3
−0

I was trying to initialize a simple two dimensional array as follows:

const arrays = Array(3).fill([]);

However, when I tried to push an entry into one of the arrays, it seems like it gets pushed to all of them for some reason:

arrays[0].push('foo');
console.log(arrays); // [ [ 'foo' ], [ 'foo' ], [ 'foo' ] ]

Why is this happening, and what can I do to fix it?

Why does this post require moderator attention?
You might want to add some details to your flag.
Why should this post be closed?

0 comment threads

1 answer

+4
−0

The problem is that the fill function is filling the array with references to the same empty array[1], and therefore modifying that array will affect every entry because all of them are actually the same entry.

To get around this, you need to explicitly create a new array for each index, for instance by using a for loop

const arrays = [];
for (let i = 0; i < 3; i++) {
    arrays.push([]);
}

arrays[0].push('foo');
console.log(arrays); // [ [ 'foo' ], [], [] ]

  1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill#description ↩︎

Why does this post require moderator attention?
You might want to add some details to your flag.

0 comment threads

Sign up to answer this question »