Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Why does pushing to one array affect all the arrays in my two-dimensional array?
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?
1 answer
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' ], [], [] ]
0 comment threads