menu

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) {
    accumulatedArray.push({
        id: id,
    })
}

finalArray.push(accumulatedArray)

accumulatedArray.length = 0 // remove elements from array

console.log(finalArray) 

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:

finalArray.push([...accumulatedArray])

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

Comments:
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) :