I have a question related to finding count of objects inside an array. My array is this:
completePositions: any = [
    {
      totalPositions: [
        { position: "CNA", count: 2 },
        { position: "LVN", count: 5 },
        { position: "RNA", count: 8 }
      ]
    },
    {
      totalPositions: [
        { position: "CNA", count: 13 },
        { position: "LVN", count: 11 },
        { position: "RNA", count: 15 }
      ]
    }
  ];
I was trying to find the total count of each position in totalPositions array, so that my final array will look like this:
totalPositionsCount = [
        { position: "CNA", count: 15 },
        { position: "LVN", count: 16 },
        { position: "RNA", count: 23 }
  ];
I created a function to sum up each position in 'totalPositons' array and push the sum to totalPositionsCount. My function does the job and I got the total count, but it changes the parent array 'completePositions' and first 'totalPositions' of 'completePositions' gets replaced by the 'totalPositionsCount' array. I tried to create a backup of 'completePositions' and use it for calculations, still both the arrays first 'totalPositions' gets replaced by 'totalPositionsCount' array.
My function to sum up the position is:
codeToShowTotalResources() {
    for (let totPos of this.completePositions) {
        for (let eachPos of totPos.totalPositions) {
            console.log("eachPos", eachPos);
            let postCountIndex = this.totalPositionsCount.findIndex(
                pos => pos.position == eachPos.position
            );
            if (postCountIndex != -1) {
                console.log("Already exists, sum up positions");
                let positionCount = this.totalPositionsCount[postCountIndex].count + eachPos.count;
                this.totalPositionsCount[postCountIndex].count = positionCount;
            } else {
                console.log("Add it for first time");
                this.totalPositionsCount.push(eachPos);
            }
        }
    }
}
If I replace this.totalPositionsCount[postCountIndex].count = positionCount; with this.totalPositionsCount[postCountIndex] = { position: eachPos.position, count: positionCount }; then it works just fine. I want to know what I was doing wrong, or is it supposed to work this way.
I've opened a sample project in stackblitz any help will be great :)
 
    