DEV Community

Cover image for Javascript Polyfill Array.sample #7
chandra penugonda
chandra penugonda

Posted on

Javascript Polyfill Array.sample #7

This problem was asked by Tencent.

Implement Array.prototype.sample() result gets a random element from array.

Examples

[1, 9, 8, 7].sample()
[1, 2, 3, 4].sample(); 
Enter fullscreen mode Exit fullscreen mode

Solution

if (!Array.prototype.sample) {
  Array.prototype.sample = function () {
    // Get a random index between 0 and length of array
    const randomIndex = Math.floor(Math.random() * this.length);

    // Return element at random index
    return this[randomIndex];
  };
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • Use Math.random() to generate a random number between 0 and 1.
  • Multiply by the length of the array to get a random index.
  • Use Math.floor() to convert to an integer index.
  • Return the element at the randomly generated index.
  • This will work for arrays of any size and return a randomly selected element each time.

Top comments (0)