Вот несколько способов выбрать случайное значение из массива:
-
Использование Math.random() и Math.floor():
const array = [/* your array here */]; const randomValue = array[Math.floor(Math.random() * array.length)]; -
Использование Math.random() и parseInt():
const array = [/* your array here */]; const randomValue = array[parseInt(Math.random() * array.length)]; -
Использование библиотеки lodash:
const _ = require('lodash'); const array = [/* your array here */]; const randomValue = _.sample(array); -
Использование пакета случайных предметов:
const randomItem = require('random-item'); const array = [/* your array here */]; const randomValue = randomItem(array); -
Использование пакета случайного выбора:
const randomPick = require('random-pick'); const array = [/* your array here */]; const randomValue = randomPick(array); -
Использование метода Array.prototype.sort():
const array = [/* your array here */]; array.sort(() => Math.random() - 0.5); const randomValue = array[0]; -
Использование алгоритма перемешивания Фишера-Йейтса:
function shuffleArray(array) { for (let i = array.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [array[i], array[j]] = [array[j], array[i]]; } } const array = [/* your array here */]; shuffleArray(array); const randomValue = array[0];