如何从数组中获取没有重复的随机项?
我有一系列元素,比如
var a = ["Mango", "Orange", "Banana", "Apple", "Grapes", "Berry", "Peach"]
我想从数组a
var random = ["Banana", "Berry", "Peach"]
答案 0 :(得分:1)
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))
答案 1 :(得分:0)
试试这个: -
var a = ["Mango","Orange","Banana","Apple","Grapes","Berry","Peach"]
b = _.shuffle(a).slice(0,5);
console.log(b);
答案 2 :(得分:0)
这应该没有任何重复:
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)
答案 3 :(得分:0)
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))
&#13;
使其灵活支持您想要的任何count
并确保唯一性