2

I have a div, that should display a random value from a predefined array, without repetition, and then, when there are no more values left, it displays a special message, like "no values left". How do I achieve that? (I'm using JQuery)

3 Answers3

1

I tried to do a small snippet. I used the Array splice() method.

var $div = $('#myDiv');

var array = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

var interval = setInterval(function(){
    if(array.length){
      var randIndex = Math.floor(Math.random()*array.length);
      var choosen = array.splice(randIndex, 1);
    } else {
      var choosen = 'No more values for you!';
      clearInterval(interval);
    } 
    $div.text(choosen);
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="myDiv"></div>
squaleLis
  • 6,116
  • 2
  • 22
  • 30
1

You can achieve that using shuffle solution :

//predefined array
var my_array = ['a', 'b', 'c', 'd', 'e', 'f'];

//Generate array of numbers from 0 to my_array.length
var numbers = Array.apply(null, {length: my_array.length}).map(Number.call, Number);

//shuffle function
function shuffle(o) {
  for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
  return o;
};

//Get array of random unique numbers
var random = shuffle(numbers);

//Display random values
for(var i=0; i<random.length;i++){
  $('#result').append(my_array[random[i]]);
  $('#result').append("<br>");
}
$('#result').append("no values left.");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 <span id='result'></span>
Community
  • 1
  • 1
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
0

I had a little go. Hope it helps https://jsfiddle.net/ch7y04v2/

// Your predefined array
var predefinedarray = ['something','else','more'];

//on click button get next random value
$('#get-next-value').click(function(){

 //if there is a value extract else reply no values left
 if(predefinedarray.length>0){
  
   // get a random value value
    var rand = predefinedarray[Math.floor(Math.random() * predefinedarray.length)];
    
    //find that value randomly in the array and remove it
    predefinedarray.splice( $.inArray(rand, predefinedarray), 1 );
    
    //add message in the div
    $('#textbox').html(rand);
  } else {
    $('#textbox').html('No values left');
  }
  
});
<div id="textbox">

</div>

<button id="get-next-value">
Get next value
</button>
Jason
  • 171
  • 9
  • nice, but I think I have to put it in a separate function or something to make it work properly: https://jsfiddle.net/qw12okuy/13/ –  Dec 10 '15 at 14:24
  • https://jsfiddle.net/qw12okuy/14/ Move the array outside of the click event if you want it to not repeat and remove the value after each click. var predefinedarray = ['something', "hello", 'else','more']; $( "#hat" ).click(function() { – Jason Dec 10 '15 at 15:11