1

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];
Silviu Burcea
  • 5,103
  • 1
  • 29
  • 43
tanaallen
  • 69
  • 1
  • 1
  • 4
  • Just filter it out after it is used – MrMythical Oct 20 '21 at 14:42
  • Please update your title to reflect the body more. Your title says that you want to pick a random value from the array, but you already did that. What you really want is to delete after usage. – MrMythical Oct 20 '21 at 14:53

2 Answers2

2

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

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>
Terry Lennox
  • 29,471
  • 5
  • 28
  • 40
0

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!")
MrMythical
  • 8,908
  • 2
  • 17
  • 45