0

I need a hand on this.

getPositionsPortfolioUpdated(){
    this.positionsWholeAccUpdated = [];
    this.positionsWholeAccUpdated = this.allPositionsFromAllAccs
    this.positionsWholeAccUpdated.forEach((pos, index) => {
        if (pos.ticker === this.ticker) {
            this.updatedPos = pos;
            this.updatedPos.direction = this.calculationData.position.updated.direction;
            this.updatedPos.size = this.calculationData.position.updated.quantity;
            this.updatedPos.value = this.calculationData.position.updated.value;
            this.positionsWholeAccUpdated.splice(index, 1)
            this.positionsWholeAccUpdated.push(this.updatedPos)
        }
    })
}

The problem is the next: When I do the slice and the push (this.positionsWholeAccUpdated.push(this.updatedPos) and this.positionsWholeAccUpdated.splice(index, 1)), is actually happening in this.allPositionsFromAllAccs too for some reason (in both arrays). Why is that happening? I created a new array so I don't touch this.allPositionsFromAllAccs at all, since I need it untouched. Any help on this?

Edit: solved with this: this.positionsWholeAccUpdated = JSON.parse(JSON.stringify(this.allPositionsFromAllAccs));

  • 2
    `this.positionsWholeAccUpdated = this.allPositionsFromAllAccs` ***does not create a new array***. It just creates a new name for the same array. – VLAZ Jul 23 '21 at 20:46
  • 1
    Also, nothing at all here is related to TS. This is just how JS works – VLAZ Jul 23 '21 at 20:47
  • Thanks for the link VLAZ. I solved it with this: this.positionsWholeAccUpdated = JSON.parse(JSON.stringify(this.allPositionsFromAllAccs)); – gaspar aufranc Jul 23 '21 at 21:05

1 Answers1

0

I see that you solved it using JSON methods to make a copy. Another alternative would be to use the spread operator. It will also make a copy for you.

this.positionsWholeAccUpdated = [...this.allPositionsFromAllAccs];

See more information here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax#spread_in_array_literals

DeborahK
  • 57,520
  • 12
  • 104
  • 129