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'
]
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'
]
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))