0

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 ?

sudo install
  • 148
  • 1
  • 1
  • 7
  • Because `finalArray.push(accumulatedArray)` is pushing that reference, it is not making a new array. – epascarello Jan 23 '23 at 21:46
  • https://stackoverflow.com/questions/7486085/copy-array-by-value – epascarello Jan 23 '23 at 21:47
  • 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 – sudo install Jan 23 '23 at 21:49

0 Answers0