-1

how can I get multiple random strings from array of strings. For example:

const arr = [
'Text1',
'Text2',
'Text3',
'Text4',
'Text5'
]

And result:

const randomStrings = [
'Text1',
'Text4'
]
Shiny Diamond
  • 105
  • 10

1 Answers1

3

You can use Math.random(). This will generate a random number between 0 and 1 (excluding 1). You can then multiply this number by the length of the array, and use Math.floor() to generate an index in the array. When we use splice, it will mutate the original array, but it ensures that there will not be duplicate values.

const arr = ['Text1', 'Text2', 'Text3', 'Text4', 'Text5']
const out = []
const elements = 2

for (let i = 0; i < elements; i++) {
  out.push(...arr.splice(Math.floor(Math.random() * arr.length), 1))
}

console.log(out)

As mentioned by Terry, it would be better to create a local copy of the array so that it is not modified. It also allows to pass parameters to choose the number of elements returned:

const arr = ['Text1', 'Text2', 'Text3', 'Text4', 'Text5']

const getRandomElements = (a, n) => {
  const l = a.slice()
  const o = []
  for (let i = 0; i < n; i++) {
    o.push(...l.splice(Math.floor(Math.random() * l.length), 1))
  }
  return o
}

console.log(getRandomElements(arr, 2))
console.log(getRandomElements(arr, 3))
console.log(getRandomElements(arr, 4))
Kobe
  • 6,226
  • 1
  • 14
  • 35
  • Just a note: this will cause `arr` to be modified. It might make more sense to abstract all that logic into a function, so that you can pass an array into the function and the function makes a local copy of the array before splicing it :) – Terry Feb 21 '20 at 09:55
  • @Terry I addressed that in my answer, I'll add a solution that doesn't modify it now :) – Kobe Feb 21 '20 at 09:56
  • No problem. I like your approach! :) It's beautiful. – Terry Feb 21 '20 at 09:58
  • @ShinyDiamond No worries. If you need more help, feel free to ask – Kobe Feb 21 '20 at 10:14