0

i have a array with numbers. i need that array value to be generated once i click on the button, while i click on the button i need to get the value random wise from the array, but the value should not be repeated.

ex, if i get a 2 from out of 5, then i should not get the 2 again. for this i wrote this function, but the values are repeating... any idea?

var ar = [0,1,2,3,4,5];
var ran = Math.floor(Math.random()*ar.length);
ar.splice(ran,1);
alert(ar.splice);

the array values should not be removed. because if i click the button again, i need to get the values like before.

i did my work like this : but the rand values are repeating, any one can correct this to get unrepeatable values to get?

 $(document).ready(function(){
        var myArray = [1,2,3,4,5];
        var mySize = 5;
        x = 0;
        while(mySize>=1){
            var rand = Math.floor(Math.random()*mySize);
            mySize--;
            alert(rand);
        }

    })
3gwebtrain
  • 14,640
  • 25
  • 121
  • 247
  • Shuffle your array. Have a look at this answer: http://stackoverflow.com/questions/962802/is-it-correct-to-use-javascript-array-sort-method-for-shuffling/962890#962890 – Felix Kling Aug 26 '11 at 10:48

3 Answers3

1

You need your array to be in an outer scope for this like:

(function(){
    var ar = [0,1,2,3,4,5];
    document.getElementById('thebutton').onclick = function(){
        alert(ar.splice(Math.floor(Math.random()*ar.length), 1));
    };
})();

JSFiddle Example

If you create your array inside the onclick function then you are just recreating the entire array every time the button is clicked.

Paul
  • 139,544
  • 27
  • 275
  • 264
  • I need the all array values to be shuffled, and the alert need to show the shuffled values. as well the shuffled values should not keep the repetatives. ex: [0,2,3,5,4,4] or like that.. – 3gwebtrain Aug 26 '11 at 10:49
0

Take a look at this demo. In this it randomizes the array values and will repeat only after all the values are utilized.

Demo

Based on the update in your question here it is take a look.

http://jsfiddle.net/MbkwK/2/

ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
0
var ar = [0, 1, 2, 3, 4, 5];
document.getElementById('thebutton').onclick = function() {
    var shuffle = [];
    var copyarr = ar.slice(0);
    var arlength = copyarr.length;
    for (i = 0; i < arlength; i++) {
        shuffle.push(copyarr.splice(Math.floor(Math.random() * copyarr.length), 1));
    }
    alert(shuffle.join(","));
};

Working demo - http://jsfiddle.net/ipr101/qLSud/1/

ipr101
  • 24,096
  • 8
  • 59
  • 61