Farid Blaster Farid Blaster - 5 months ago 19
Node.js Question

how to make random percentage with dynamic array?

lets say we have datas:

var datas = [{animal:"chicken"}, {animal: "cow"}, {animal: "duck"}];
var after_massage = [];

datas.forEach(function(key){

after_massage.push({animal: key.animal}, {percentage: randomPercent(); })

})


Right now i dont know how to give each object got random percentage and total of 3 object cant be more than 100% percent

Answer

You can accomplish this by keeping track of a max number that your random number can hit and then keep decrementing. Theoretically, this can go on infinitely:

var datas = [{animal:"chicken"}, {animal: "cow"}, {animal: "duck"}];
var after_massage = [];
var max = 1;

var getRandomPercent = function(max) {
    var percentage = Math.random() * (max - 0) + 0;
    // every time we generate a random number, we'll decrement
    max = max - percentage;
    return percentage;
}

datas.forEach(function(key){
   after_massage.push({animal: key.animal, percentage: getRandomPercent(max) })
 });

console.log(after_massage);

See JSFiddle

Comments