Answer the question
In order to leave comments, you need to log in
How to make a percentage probability of displaying a particular picture from 2 arrays?
There are 2 arrays
const truePhotos = ['1 фото', '2 фото', '3 фото','4 фото',...'100 фото',]
const funnyPhotos = ['1 фото', '2 фото']
function getPhoto() {
return truePhotos[Math.floor(Math.random() * truePhotos.length)]
}
Answer the question
In order to leave comments, you need to log in
function weightedRandom(arr, weightKey, valueKey) {
const weightsSum = arr.reduce((acc, n) => acc + n[weightKey], 0);
return () => {
const rand = Math.random() * weightsSum;
let sum = 0;
return arr.find(n => (sum += n[weightKey]) > rand)[valueKey];
};
}
const getRandomPhotosArray = weightedRandom([
[ 9, truePhotos ],
[ 1, funnyPhotos ],
], 0, 1);
function getPhoto() {
const photos = getRandomPhotosArray();
return photos[Math.random() * photos.length | 0];
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question