Kunal Vashist
Kunal Vashist

Reputation: 2471

Random item from array with no repeat using javascript?

How to get random items from an array with no repeat?

I have an array of elements like

var a = ["Mango", "Orange", "Banana", "Apple", "Grapes", "Berry", "Peach"]

I want to get 3 random items from array a

var random = ["Banana", "Berry", "Peach"]

Upvotes: 1

Views: 4692

Answers (5)

tranvantai141
tranvantai141

Reputation: 1

i would like to improve the Willem van der Veen's answer because his code might return undefined. It stems from the fact that the arrayClone takes out the random item but random number still in the range of the previous index length. Hence, the solution is we have to decrease the arrayClone's length too:

    const array = [0, 1 ,2 ,3 ,4, 5, 6, 7, 8 , 9]

    const arrayClone = array.slice()

    let arrayLength = array.length

    let newArray = []

    for (  let i = 0; i < 5; i++) {
        let arr = arrayClone[Math.floor(Math.random() * arrayLength)]

        arrayLength--

        let index = arrayClone.indexOf(arr)

        arrayClone.splice(index, 1)

        newArray.push(arr)
     }


      console.log(newArray)

Upvotes: 0

vicky patel
vicky patel

Reputation: 705

var a = ["Mango","Orange","Banana","Apple","Grapes","Berry","Peach"]
var res = a.sort(function() {
  return 0.5 - Math.random();
});
console.log(res.slice(a,3))

Upvotes: 1

Mr. Roshan
Mr. Roshan

Reputation: 1805

Try this:-

var a = ["Mango","Orange","Banana","Apple","Grapes","Berry","Peach"]
b = _.shuffle(a).slice(0,5);
console.log(b);

Upvotes: 0

Willem van der Veen
Willem van der Veen

Reputation: 36620

This should work without any duplicates:

const a = ["Mango","Orange","Banana","Apple","Grapes","Berry","Peach"]
const b = a.slice()
const newArr = [];

for(let i= 0; i<3; i++){
 let arr = b[Math.floor(Math.random()*b.length)];
  
 let index = b.indexOf(arr);
  
  b.splice(index, 1 );
  
  newArr.push(arr)
  
}

console.log(newArr)

Upvotes: 0

Isaac
Isaac

Reputation: 12874

var a = ["Mango","Orange","Banana","Apple","Grapes","Berry","Peach"];

function searchRandom(count, arr){
  let answer = [], counter = 0;
 
  while(counter < count){
    let rand = arr[Math.floor(Math.random() * arr.length)];
    if(!answer.some(an => an === rand)){
      answer.push(rand);
      counter++;
    }
  }
  
  return answer;
}

console.log(searchRandom(3,a))

Making it flexible to support any count you want and ensured uniqueness

Upvotes: 2

Related Questions