Reputation: 25
I'm trying to build my own Discord bot and I want it to send some random things from an array i already have, but don't want them to be the same (should be different every time). For example, I have 5 things in my array and I want to reply with 3 different elements from the array.
This is my code at the moment:
var question = ["answer1", "answer2", "answer3", "answer4", "answer5"];
var temparray = [];
for(i=0;i<3;i++){
for(j=0;j<domande.length;j++){
temparray[i] = domande[Math.floor(Math.random() * domande.length)];
temparray[j] = temparray[i];
if(!temparray[i] === temparray[j]){
}
}
console.log(temparray[i]);
}
Are 2 for way to much, or am I missing something there?
Upvotes: 1
Views: 533
Reputation: 89314
You can shuffle the array and then take the first couple of elements. Here is an example using the Fisher-Yates Shuffle.
var question = ["answer1", "answer2", "answer3", "answer4", "answer5"];
for(let i = question.length - 1; i > 0; i--){
let idx = Math.floor(Math.random() * (i + 1));//or Math.random() * (i + 1) | 0
let temp = question[idx];
question[idx] = question[i];
question[i] = temp;
}
let randomValues = question.slice(0, 3);
console.log(randomValues);
Alternatively, a destructuring assignment can be used to facilitate swapping the elements.
var question = ["answer1", "answer2", "answer3", "answer4", "answer5"];
for(let i = question.length - 1; i > 0; i--){
let idx = Math.floor(Math.random() * (i + 1));//or Math.random() * (i + 1) | 0
[question[i], question[idx]] = [question[idx], question[i]];
}
let randomValues = question.slice(0, 3);
console.log(randomValues);
Upvotes: 3