Questions & Answers

Pushing object into Array of Arrays retains pointer to original object

I was wondering if anyone could help provide context on this one.

With the below example:

const finalArray: any[][] = []
const accumulatedArray: any[] = []

const ids = ['1','2']
for (const id of ids) {
        id: id,


accumulatedArray.length = 0 // remove elements from array


The above code will output [ [] ], which took me by surprise, I was expecting to see [ [ { id: '1' }, { id: '2' } ] ] but I can achieve this by creating a new array using a spread operator:


question is Why does the element in the array of arrays (finalArray) point to the accumulatedArray ?

2023-01-23 23:10:13
Because finalArray.push(accumulatedArray) is pushing that reference, it is not making a new array.
2023-01-23 23:10:13
Not sure why I thought it would work differently because it was an array of arrays, as opposed to just passing a reference with a standard array. Fair enough, thanks @epascarello
Answers(0) :