josh kelben

josh kelben

  • NA
  • 5
  • 581

Can someone explain me why both objects changing?

Jun 14 2021 2:13 PM

If I execute the following code to summaryze my list and values, my first list "animals2" get changed somehow and I dont know why.

With the command "uanimals2.forEach(x => {x.amount = 0});" i only want to change the list "uanimals2". Can someone explain me why? 

Thanks in advance!

const animals2: {name: string, amount: number}[] = [
    {name: "mouse", amount: 1},
    {name: "cat", amount: 1},
    {name: "dog", amount: 1},
    {name: "cow", amount: 1},
    {name: "mouse", amount: 2},
    {name: "cat", amount: 2},
    {name: "dog", amount: 2},
]
function summaryze(liste: {name: string, amount: number}[]) {
  let uanimals2: {name: string, amount: number}[] = []
  liste.forEach(x => {
    if (uanimals2.some(elem =>{
        return JSON.stringify(x.name) === JSON.stringify(elem.name);
      })) {}
    else
        uanimals2.push(x)
});
  return uanimals2
}let uanimals2 = summaryze(animals2)
uanimals2.forEach(x => {
  x.amount = 0
});console.log("----")
for (let x = 0; x < animals2.length; x++) {
  console.log(animals2[x].name + animals2[x].amount) 
}
console.log("----")
for (let x = 0; x < uanimals2.length; x++) {
  for (let y = 0; y < animals2.length; y++) {
    if (uanimals2[x].name === animals2[y].name) {
      uanimals2[x].amount = uanimals2[x].amount + animals2[y].amount
    }
  }
}
console.log("Tiere + Anzahl:" + JSON.stringify(uanimals2))
console.log("----")
for (let x = 0; x < animals2.length; x++) {
  console.log(animals2[x].name + animals2[x].amount) 
}
console.log("----")

Answers (1)