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
?