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

137
Views
Randomize wordset javascript array

I found the following code for randomization of one word but what I need is randomization of a word pair 2 words. How can I do this?

let words = ["monitor", "program", "application", "keyboard", "javascript", "gaming", "network"];

let getRandomWord = function () {
    return words[Math.floor(Math.random() * words.length)];
};

let word = getRandomWord();

console.log(word);

document.getElementById("word").textContent = word;
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

I hope the commented code below helps you:

let words = ["monitor", "program", "application", "keyboard", "javascript", "gaming", "network"];

let getRandomWord = function () {
    return words[Math.floor(Math.random() * words.length)];
};

//generating first word
let word1 = getRandomWord();
let word2
do{
    //getting the second word and making sure it is diferent from the first word
    word2 = getRandomWord();
}while(word1==word2)

console.log(word1, word2);
document.getElementById("word").textContent = word1 + ' ' + word2;
about 4 years ago · Juan Pablo Isaza Report

0

you can simply shuffle your array

const words = 
  [ 'monitor', 'program', 'application', 'keyboard'
  , 'javascript', 'gaming', 'network'
  ]
for (let i = words.length; --i;)  // shuffle Array
  {
  let j = Math.floor(Math.random() * (i + 1));
  [words[i], words[j]] = [words[j], words[i]]
  }

// get 2 random words
console.log( words[0], words[1] )

about 4 years ago · Juan Pablo Isaza Report

0

A standard algorithm to select a random number, say r elements from an array, n long is as follows - the trick is to move the last element to the position you just selected then reduce n by 1.

    function select(arr,r){
        let out=[];
        let n=arr.length;
        for (let i=0;i<r;i++){
            let j=Math.floor(Math.random()*n);
            out.push(arr[j])
            if(j<n-1) arr[j]=arr[n-1];
            n--;
        }
        return out;   //contains the random selection
    }
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!