Vitaliy Avdyeyev
Vitaliy Avdyeyev

Reputation: 37

How to write a function, which creates an array of objects of certain length? Object has custom generated data

I have an object with randomly generated data:

var obj = {
   price: getRandomNumberRange(10, 200),
   rooms: getRandomNumberRange(1, 5)
   };

where

var getRandomNumberRange = function (min, max) {
  return Math.floor(Math.random() * (max - min) + min);
};

I keep trying and failing to write a function, which will allow to create an array of 4 objects, so each objects' data will be regenerated at the time of creation. My function:

var createArr = function () {
   var arr = [];
      for (var i = 0; i < 5; i++) {
      arr.push(obj);
      }
   return arr;
};

In other words I expect to get this kind of array:

var arr = [{price:40, rooms:2}, {price:23, rooms:4}, {price:99, rooms:2}, {price:191, rooms:3}];

But I keep getting this:

var arr = [{price:40, rooms:2}, {price:40, rooms:2}, {price:40, rooms:2}, {price:40, rooms:2}];

Will appreciate your help!

UPD. Thanks to everyone who suggested more complex way to solve my problem. As soon as I progress in JS I will recheck this thread again!

Upvotes: 2

Views: 50

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386560

It looks like you reuse the object for pushing over and over and because of the same object, it pushes the same object reference with the latest values.

To overcome this, you need to create a new object for each loop and assign the random values with short hand properties.

// inside the loop

let price = getRandomNumberRange(10, 200),
    rooms = getRandomNumberRange(1, 5);

array.push({ price, rooms }); // short hand properties

Upvotes: 2

Related Questions