Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

189
Views
Pick Random Text from an Array

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];
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report

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!")
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!