1

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]);
                    }

I dont want this to happen

Are 2 for way to much, or am I missing something there?

1 Answer 1

3

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.