Random object from multiple arrays with percent chance in JS
Posted: 25 Oct 2020, 12:26
I have 3 arrays of objects in JavaScript:
One temporary array where I will store random objects from arrays:
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?
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"}
]
Code: Select all
const tempArray = []
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?