0

I have a number of elements in an array and I want some of them to have a higher likelihood of being chosen, than other ones. In this jsfiddle example, I made a simple array and function that will allow certain elements to be chosen far greater than other ones. However, the array I used was very small because it only had 5 elements. I'm thinking about using around 50 or so elements.

Like This

 "job":["Teacher", "Doctor","Nurse","Unemployed","Engineer","Mechanic", "Welder", "Cashier","Police Officer","Waiter","Cook",
       "Security Guard", "Construction Worker","Truck Driver","Accountant","Carpenter","Operations Manager","Lawyer","Electrician",
       "Bartender","Lawnman"]

So I don't have time to make an if or else if statement for everyone of the array elements. There has to be a better way to do this right?

black_yurizan
  • 407
  • 2
  • 7
  • 19

1 Answers1

4

I created a jsbin with some changes. I hope it will work and you can extend the list as you wish.

http://jsbin.com/muwejehete/edit?html,js,output

// first create a list options with respective weight or likelyhood
var myarr = [{
   load: 1,
   name: "nothing, because you are broke"
   }, {
   load: 5,
   name: "1000 dollars"
   }, {
   load: 2,
   name: "10,000 dollars"
   }, {
   load: 4,
   name: "100,000 dollars"
   }, {
   load: 7,
   name: "a million dollars"
 }];
 // create another array to store final options 
 var list = [];
 //  repeat an option as amny times as given by weight
 myarr.forEach(function(item) {
   for (var i = 1; i < item.load; i++) {
     list.push(item.name);
   }
 });

 // Now shuffle the options because same options are together in array, I want to separate them for better randomization.
 list = shuffle(list);


 document.getElementById('btn').onclick = function() {
   // pick an index from options list
   var num = Math.floor(Math.random() * list.length);
   document.getElementById("result").innerHTML = "You are worth " +      list[num];
 };

https://stackoverflow.com/a/6274398/5567387

 function shuffle(array) {
   var counter = array.length;

   // While there are elements in the array
   while (counter > 0) {
     // Pick a random index
     var index = Math.floor(Math.random() * counter);

     // Decrease counter by 1
     counter--;

     // And swap the last element with it
     var temp = array[counter];
     array[counter] = array[index];
     array[index] = temp;
   }

   return array;
 }
Community
  • 1
  • 1
Zohaib Ijaz
  • 21,926
  • 7
  • 38
  • 60