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.
Post History
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 push...
#2: Post edited
- I was trying to initialize a simple two dimensional array as follows:
- ```javascript
- 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:
- ```javascript
array[0].push('foo');console.log(array); // [ [ 'foo' ], [ 'foo' ], [ 'foo' ] ]- ```
- Why is this happening, and what can I do to fix it?
- I was trying to initialize a simple two dimensional array as follows:
- ```javascript
- 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:
- ```javascript
- arrays[0].push('foo');
- console.log(arrays); // [ [ 'foo' ], [ 'foo' ], [ 'foo' ] ]
- ```
- Why is this happening, and what can I do to fix it?
#1: Initial revision
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: ```javascript 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: ```javascript array[0].push('foo'); console.log(array); // [ [ 'foo' ], [ 'foo' ], [ 'foo' ] ] ``` Why is this happening, and what can I do to fix it?