2

My code there are no of divs here, I have to select 5 randomaly at a time

<div id="#jpId1"></div>
<div id="#jpId2"></div>
<div id="#jpId3"></div>
<div id="#jpId4"></div>
<div id="#jpId5"></div>
<div id="#jpId6"></div>
<div id="#jpId7"></div>
<div id="#jpId8"></div>
<div id="#jpId9"></div>
<div id="#jpId10"></div>
<div id="#jpId11"></div>

I want in array (r), values of id's with no repeat but the values are repeated.... Any help is appreciable ... I have to use these ids for specific purpose

var itemp = ["#jpId1", "#jpId2", "#jpId3", "#jpId4", "#jpId5", "#jpId6", "#jpId7","#jpId8", "#jpId9", "#jpId10", "#jpId11"]
for (var i = 0; i < 5; i++) {
    var r = itemp[Math.floor(Math.random() * itemp.length)];
    alert(r);
}
Rahul Desai
  • 15,242
  • 19
  • 83
  • 138
Jot Dhaliwal
  • 1,470
  • 4
  • 26
  • 47

4 Answers4

1

Try this (splice removes the selected element from the source array) :

var r = [];
for (var i = 0; i < 5; i++) {
    r.push(itemp.splice(
        Math.floor(Math.random() * itemp.length), 1
    )[0]);
}
alert(r);
0

When you get the first random value from the array use the splice method to remove the that particluar value from the array.

var random = Math.floor(Math.random() * item.length);
item[random];

Then remove that particular value from array.

item.splice(random,1);

Use this in a loop it will give you everytym new value.

rrugbys
  • 282
  • 1
  • 10
0

You can check below code:

var nums = ["#jpId1", "#jpId2", "#jpId3", "#jpId4", "#jpId5", "#jpId6", "#jpId7","#jpId8", "#jpId9", "#jpId10", "#jpId11"],
ranNums = [],
i = 5,
j = 0;
k = 10;

while (i--) {
   j = Math.floor(Math.random() * (k+1));
   ranNums.push(nums[j]);
   nums.splice(j,1);
   k--;
}

console.log(ranNums);

And you can find link here http://jsfiddle.net/8Xb5g/1/

Bhavesh Parekh
  • 212
  • 2
  • 11
0

Here is the code:

var itemp = ["#jpId1", "#jpId2", "#jpId3", "#jpId4", "#jpId5", "#jpId6", "#jpId7","#jpId8", "#jpId9", "#jpId10", "#jpId11"];
id_arr=Array();
for (var i = 0; i < 5; i++) {
    var r = itemp[Math.floor(Math.random() * itemp.length)];
    if($.inArray(r, id_arr)>-1)
    {
        alert ("duplicate "+r+", hence discarded");
        i--;
        continue;
    }
    else
        id_arr.push(r);
    alert(r);
}
console.log(id_arr)

Fiddle

Rajesh Paul
  • 6,793
  • 6
  • 40
  • 57