Nabel
Nabel

Reputation: 1956

forEach loop assigns the same random number

In typescript, I am trying to assign a random number to a property of each object in an array. I have tried the following code

uniqueItems.forEach(unique => {
  unique.humanCode = Math.floor(1000 + Math.random() * 9000).toString();
});

If I console.log inside the forEach loop, I get a different number but when I console.log the array of objects after the forEach, all of the random numbers are the same.

Edit: I had originally created my array of objects by using

for (let i = 0; i < this.quantity; i++) {
  this.uniqueItems.push(uniqueItem);
}

This made an array of the same object. This meant that my array was being assigned the last random number. I fixed this by using the spread operator when I created my array.

for (let i = 0; i < this.quantity; i++) {
  this.uniqueItems.push({ ...this.uniqueItem });
}

Upvotes: 0

Views: 941

Answers (2)

Raju
Raju

Reputation: 2509

I have tried the below code and it works for me.

let uniqueItems = [{
    humanCode: 0,
  },
  {
    humanCode: 0,
  },
  {
    humanCode: 0,
  },
]
uniqueItems.forEach(unique => {
  unique.humanCode = Math.floor(1000 + Math.random() * 9000).toString();
});

console.log(uniqueItems);

Upvotes: 0

KiaiFighter
KiaiFighter

Reputation: 667

You can use map to iterate over your items and return a new object for each item in the array. This will also ensure you are no updating the object by reference. You should read about mutability in JavaScript. It's an important concept in JS

uniqueItems.map(unique => ({
  ...unique, 
  humanCode: Math.floor(1000 + Math.random() * 9000).toString(),
}));

Upvotes: 4

Related Questions