I have made it, but is it possible to show it only one time and delete it from the list for each thing?
For example, it first shows the "first" When it's been sent, I want to send the other 3 messages, and when it's empty, it indicates that there aren't any [answers] in the list.
const messages = ["first", "two", "three", "four"]
const randomMessage = messages[Math.floor(Math.random() * messages.length) - 1];
CodePudding user response:
After using it, you can find the index of the element picked, then remove it right after.
const messages = ["first", "two", "three", "four"]
const index = Math.floor(Math.random() * messages.length)
const randomMessage = messages[index]
messages.splice(index, 1)
//rest of what you are going to do with 'randomMessage'
As for checking if it is empty, just check either messages.length
or randomMessage
. Both will be falsy if the array is empty (messages.length
will be 0
and randomMessage
will be undefined
)
if (!messages.length) console.log("The array is empty!")
CodePudding user response:
I'd suggest using a shuffling algorithm to shuffle your messages, you can then use Array.shift() to pick off messages one by one.
The shuffle()
function here is a basic Fisher–Yates / Knuth shuffle.
function shuffle(arr) {
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return arr;
}
const messages = ["first", "two", "three", "four"];
const randomizedMessages = shuffle(messages);
let i = 0;
// Take messages one by one using Array.pop()
while(randomizedMessages.length) {
console.log(`Message #${ i}:`, randomizedMessages.shift());
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Or using lodash shuffle:
const messages = ["first", "two", "three", "four"];
const randomizedMessages = _.shuffle(messages);
let i = 0;
while(randomizedMessages.length) {
console.log(`Message #${ i}:`, randomizedMessages.shift());
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" referrerpolicy="no-referrer"></script>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>