Search code examples
javascriptarrayssplice

take random string from array, put it in new array, then put it back in old array later


I'm trying to make a sentence that chooses random items from an array twice. The first chosen item is temporarily removed from the array so it can't be chosen again, then the second item is also randomly chosen and added to the sentence. Then, to reset it so I can do this again later, I try to add back the first chosen item in to its initial array.

The issue is that, when I do this, the chosenWord1 displays in the sentence as a string as I hoped, but chosenWord2 displays an index number instead.

array = ["word","another word", "yet another word"];

/* put a random word from the array in its own value and then 
remove it from the array so it can't be chosen in next step */

let chosenWord1 = array.splice(Math.random() * array.length, 1)[0];

/* pick another random word from the same, altered array */

let chosenWord2 = Math.floor(Math.random() * array.length);

/* a function that puts a sentence on the webpage concatenating the strings 
from chosenWord1 and chosenWord2 goes here. then... */

/* add back the previously removed word so this process can repeat again 
with the same items in the array as there was before anything was done to it */

array.splice(1,0,chosenWord1);

Also, if there's some more sensible way I can structure this, please let me know. I'm still pretty new to this.


Solution

  • I don't know if this is what you need, but this extracts two random words repeatedly without taking them out from the original array. The for loop is used to show how it works with different words.

    const array = ["word", "another word", "yet another word"];
    const randomNumber = (key) => Math.floor(Math.random() * key);
    for (let i = 0; i < 10; i++) {
      const { [randomNumber(array.length)]: wordOne, ...rest } = array;
      const { [randomNumber(array.length - 1)]: wordTwo } = Object.values(rest);
    
      console.log(`${wordOne} and ${wordTwo}`);
    }