How to Select 3 Unique Items From A Dynamic Array

- 1 answer

Ad

I have a Dynamic array which a sample of that looks like

var nums=[25,12,23,47,55,116,17,80,92,150,191,142,13,124,15,176,187,18,19,20,21,30,31];

Can you please let me know how I can select 3 unique items from the nums and load them to a new array using jQuery of pure JS?

I tried this already

 var arr = []
 while(arr.length < 3){
   var randomnumber=Math.ceil(Math.random()*nums.length)
   var found=false;
   for(var i=0;i<arr.length;i++){
    if(arr[i]==randomnumber){found=true;break}
  }
   if(!found)arr[arr.length]=randomnumber;
 }

but I am not getting what I want

Ad

Answer

Ad
while (arr.length < 3) {
  var randomIndex = Math.floor(Math.random()*nums.length);
  if (arr.indexOf(nums[randomIndex]) === -1) {
    arr.push(nums[randomIndex])
  }
}

Here I create a new random index each time we go through the loop, and then check if that number is already in our result array. If it is not, we push it in, otherwise we just start over.

Ad
source: stackoverflow.com
Ad