How to use Array.prototype.reduce Method In Javascript
Another approach to select a random element from an array in JavaScript is by using the reduce method in combination with Math.random(). This method involves iterating through the array and selecting a random element based on a cumulative probability.
Example: In this example, we will use the reduce method to randomly select an element from an array.
function getRandomElementWithReduce(array) {
return array.reduce((selected, item) => {
return Math.random() < 1 / (array.length) ? item : selected;
}, array[0]);
}
// Example usage
const sampleArray = [100, 200, 300, 400, 500];
const randomItemWithReduce = getRandomElementWithReduce(sampleArray);
console.log(randomItemWithReduce);
Output
100
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
How to select a random element from array in JavaScript ?
We are going to learn how can we select a random element from an array in JavaScript. we will be given an array and we need to print a random element from that array.
Selecting a random element from an array is a common task, especially in scenarios where you need to introduce randomness or unpredictability into your code. Whether you’re building a game, conducting statistical analysis, or implementing a feature that requires random selection, knowing how to pick a random element from an array is important.
These are the following approaches for solving this problem:
Table of Content
- Using Math.random() function
- Using custom function
- Using Lodash _.sample method
- Using Array.splice() with Math.random()
- Using Array destructuring and Math.floor()