Random object from multiple arrays with percent chance in JS

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
Marius
Posts: 106

Random object from multiple arrays with percent chance in JS

I have 3 arrays of objects in JavaScript:

Code: Select all

const fruits = [
{name: "Banana"}, 
{name: "Apple"}, 
{name: "Peach"}
]

const car = [
{name: "Audi"}, 
{name: "Bentley"}
]

const books = [
{name: "Alice in wonderland"}, 
{name: "Deep in the dark"}, 
{name: "Hunting Show"}
]
One temporary array where I will store random objects from arrays:

Code: Select all

const tempArray = []
I want to get random object from random array.

50% percentage chance that I get random object from fruits.
30% percentage chance that I get random object from car array.
20% percentage chance that I get random object from books array.

Example:
- Random chance is 50% -> random object from array fruits is pushed to tempArray and tempArray should have object with bane "Banana".
- Random chance is 20% -> Random object from array books is pushed to tempArray and tempArray should have object with name "Hunting Show".

How can I do it in javascript?

Admin
You need to get two random numbers:
- the first to decide which group to pick,
- the second to pick an item from that.

We generate a random number from 1 to 100.
- A number from 1 to 20 would pick a random element from the books array,
- a number from 21 to 50 would pick a random element from the car array,
- a number from 51 to 100 would pick a random element from the fruits array.

Code: Select all

const fruits = [
  {name: "Banana"}, 
  {name: "Apple"}, 
  {name: "Peach"}
]

const car = [
  {name: "Audi"}, 
  {name: "Bentley"}
]

const books = [
  {name: "Alice in wonderland"}, 
  {name: "Deep in the dark"}, 
  {name: "Hunting Show"}
]

const tempArray = []

let randomNumber = Math.floor((Math.random() * 100) + 1); // 1 to 100

if (randomNumber < 21) {
  let randomIndex = Math.floor(Math.random() * books.length); // 0 to 3
  tempArray.push(books[randomIndex]);
}
else if (randomNumber < 51) {
  let randomIndex = Math.floor(Math.random() * car.length); // 0 or 1
  tempArray.push(car[randomIndex]);
}
else {
  let randomIndex = Math.floor(Math.random() * fruits.length); // 0 to 2
  tempArray.push(fruits[randomIndex]);
}

console.log('tempArray: ' + JSON.stringify(tempArray));

Similar Topics