Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating an array of objects with random number of properties

I am trying to create an array of objects that will be populated by random properties.
I want the objects all to look like this

{ systemStar: "something random", planets: ["random1", "random2", etc]}
Currently I have the following code

const letThereBeLight = () => {
  let universe = []
  const starNumber = 5;
  let randomNumberOfPlanets = Math.floor(Math.random() * 6);
  for (let i = 0; i < starNumber; i++) {
    universe.push({
      systemStar: starList[Math.floor(Math.random() * lengthOfStarList)],
      systemPlanets: [planetList[Math.floor(Math.random() * lengthOfPlanetList)]]
    })

  }

  console.log(universe)
}

This does a great job in creating the objects I want with the following format, however the systemPlanets is only one, instead of a random number. I have tried to do a double for loop but the syntax was eluding me.
How can I get an array of random strings inside of my for loop?

Added variables for clarity

let starList = [
  "Red-Giant",
  "Red-Supergiant",
  "Blue-Giant",
  "White-Dwarf",
  "Yellow-Dwarf",
  "Red-Dwarf",
  "Brown-Dwarf",
];
let planetList = [
  "Rocky",
  "Temperate",
  "Ocean",
  "Frozen",
  "Lava",
  "Gas"
];

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try using Array.from({length:5}) to create an array of 5 elements.
and replace 5 with a random number by using Math.random() * 5 Math.floor() method to round it down to near number, add add one to at least create one planet. then map them to values in source array `planetList.

let starList = [
  "Red-Giant",
  "Red-Supergiant",
  "Blue-Giant",
  "White-Dwarf",
  "Yellow-Dwarf",
  "Red-Dwarf",
  "Brown-Dwarf",
];
let planetList = [
  "Rocky",
  "Temperate",
  "Ocean",
  "Frozen",
  "Lava",
  "Gas"
];
let lengthOfStarList = starList.length;
let lengthOfPlanetList = planetList.length;
let universe = []
const starNumber = 5;
for (let i = 0; i < starNumber; i++) {
    universe.push({
      systemStar: starList[Math.floor(Math.random() * lengthOfStarList)],
      systemPlanets: Array.from({length:Math.floor(Math.random() * 5)+1}).map(x=>planetList[Math.floor(Math.random() * lengthOfPlanetList)])
    })
}
console.log(universe)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading