Get a Random Item from a Javascript Array

Get a random item from a JavaScript array

As a JavaScript developer, you may often come across situations where you need to retrieve a random item from an array. Whether you’re building a game, a random quote generator, or simply need to display a random element on your website, knowing how to get a random item from an array is a useful skill to have. In this article, we’ll explore different approaches to accomplish this task.

Method 1: Math.random()

One way to get a random item from an array is by using the Math.random() function combined with the array’s length. This method involves generating a random index within the range of the array’s length and returning the element at that index.

const array = [1, 2, 3, 4, 5];

function getRandomItem(array) {
  const randomIndex = Math.floor(Math.random() * array.length);
  return array[randomIndex];
}

const randomItem = getRandomItem(array);
console.log(randomItem);

This code snippet uses the getRandomItem() function to retrieve a random item from the array. The Math.random() function generates a random decimal number between 0 and 1. By multiplying it with the length of the array and flooring the result using Math.floor(), we obtain a random index within the range of the array’s length. Finally, we return the element at that index.

Method 2: Using the Fisher-Yates Shuffle Algorithm

Another approach to getting a random item from an array is by shuffling the array using the Fisher-Yates shuffle algorithm and selecting the first element. This method ensures a truly random distribution of elements within the array.

const array = [1, 2, 3, 4, 5];

function getRandomItem(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]];
  }
  return array[0];
}

const randomItem = getRandomItem(array);
console.log(randomItem);

In this code snippet, the getRandomItem() function shuffles the elements of the array using the Fisher-Yates shuffle algorithm. It iterates over the array from the last element to the second element, generating a random index within the remaining unshuffled portion of the array and swapping the current element with the element at the random index. Finally, it returns the first element of the shuffled array.

Both methods presented above will give you a random item from a JavaScript array. Choose the method that best suits your needs and integrate it into your code to add randomness to your applications!

Final Output:

<

pre>

Get a random item from a JavaScript array As a JavaScript developer, you may often come across situations where you need to retrieve a random item from an array. Whether you're building a game, a random quote generator, or simply need to display a random element on your website, knowing how to get a random item from an array is a useful skill to have. In this article, we'll explore different approaches to accomplish this task. Method 1: Math.random() One way to get a random item from an array is by using the Math.random() function combined with the array's length. This method involves generating a random index within the range of the array's length and returning the element at that index. const array = [1, 2, 3, 4, 5]; function getRandomItem(array) { const randomIndex = Math.floor(Math.random() * array.length); return array[randomIndex]; } const randomItem = getRandomItem(array); console.log(randomItem); This code snippet uses the getRandomItem() function to retrieve a random item from the array. The Math.random() function generates a random decimal number between 0 and 1. By multiplying it with the length of the array and flooring the result using Math.floor(), we obtain a random index within the range of the array's length. Finally, we return the element at that index. Method 2: Using the Fisher-Yates Shuffle Algorithm Another approach to getting a random item from an array is by shuffling the array using the Fisher-Yates shuffle algorithm and selecting the first element. This method ensures a truly random distribution of elements within the array. < pre>const array = [1, 2, 3, 4, 5]; function getRandomItem(array) { for (let i = array.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [array[i Share this:FacebookX Related Posts: Getting a Random Value from a Javascript Array Getting a random value from a JavaScript array As a JavaScript developer, you may often come across situations where you... Generate Random String/Characters in Javascript Generating random strings or characters in JavaScript can be useful in various scenarios, such as generating unique identifiers, creating random... Generate Random Number Between Two Numbers in Javascript Generating a random number between two given numbers is a common task in JavaScript. In this blog post, we will... Generating Random Whole Numbers in Javascript in a Specific Range Generating random whole numbers in JavaScript is a common task, but what if you want to generate these numbers within...
Posted September 9, 2023 in Common Problems, JavaScript, Uncategorized by Nikolas H. Tags: Comments Leave a Reply Cancel replyYour email address will not be published. Required fields are marked *Comment * Name * Email * Website Save my name, email, and website in this browser for the next time I comment.
JS Duck Privacy Policy © Copyright 2023
window.WPCOM_sharing_counts = {"https:\/\/js-duck.com\/get-a-random-item-from-a-javascript-array-2\/":962}; var ce4wp_form_submit_data = {"siteUrl":"https:\/\/js-duck.com","url":"https:\/\/js-duck.com\/wp-admin\/admin-ajax.php","nonce":"3a735f2bd8","listNonce":"e82069c2aa","activatedNonce":"c92e97abc0"}; ( function() { var skipLinkTarget = document.querySelector( 'main' ), sibling, skipLinkTargetID, skipLink; // Early exit if a skip-link target can't be located. if ( ! skipLinkTarget ) { return; } /* * Get the site wrapper. * The skip-link will be injected in the beginning of it. */ sibling = document.querySelector( '.wp-site-blocks' ); // Early exit if the root element was not found. if ( ! sibling ) { return; } // Get the skip-link target's ID, and generate one if it doesn't exist. skipLinkTargetID = skipLinkTarget.id; if ( ! skipLinkTargetID ) { skipLinkTargetID = 'wp--skip-link--target'; skipLinkTarget.id = skipLinkTargetID; } // Create the skip link. skipLink = document.createElement( 'a' ); skipLink.classList.add( 'skip-link', 'screen-reader-text' ); skipLink.href = '#' + skipLinkTargetID; skipLink.innerHTML = 'Skip to content'; // Inject the skip link. sibling.parentElement.insertBefore( skipLink, sibling ); }() ); var hcbVars = {"showCopyBtn":"1","copyBtnLabel":"Copy code to clipboard"}; _stq = window._stq || []; _stq.push([ "view", JSON.parse("{\"v\":\"ext\",\"blog\":\"223076394\",\"post\":\"962\",\"tz\":\"0\",\"srv\":\"js-duck.com\",\"j\":\"1:14.5\"}") ]); _stq.push([ "clickTrackerInit", "223076394", "962" ]); wp.i18n.setLocaleData( { 'text direction\u0004ltr': [ 'ltr' ] } ); var _wpUtilSettings = {"ajax":{"url":"\/wp-admin\/admin-ajax.php"}}; var dracula = {"homeUrl":"https:\/\/js-duck.com","ajaxUrl":"https:\/\/js-duck.com\/wp-admin\/admin-ajax.php","pluginUrl":"https:\/\/js-duck.com\/wp-content\/plugins\/dracula-dark-mode","settings":{"excludes":[""],"colorMode":"presets","preset":"dracula"},"isPro":"","upgradeUrl":"https:\/\/js-duck.com\/wp-admin\/admin.php?billing_cycle=annual&page=dracula-pricing","nonce":"38f24a32ff"}; var sharing_js_options = {"lang":"en","counts":"1","is_stats_active":"1"}; var windowOpen; ( function () { function matches( el, sel ) { return !! ( el.matches && el.matches( sel ) || el.msMatchesSelector && el.msMatchesSelector( sel ) ); } document.body.addEventListener( 'click', function ( event ) { if ( ! event.target ) { return; } var el; if ( matches( event.target, 'a.share-facebook' ) ) { el = event.target; } else if ( event.target.parentNode && matches( event.target.parentNode, 'a.share-facebook' ) ) { el = event.target.parentNode; } if ( el ) { event.preventDefault(); // If there's another sharing window open, close it. if ( typeof windowOpen !== 'undefined' ) { windowOpen.close(); } windowOpen = window.open( el.getAttribute( 'href' ), 'wpcomfacebook', 'menubar=1,resizable=1,width=600,height=400' ); return false; } } ); } )(); var windowOpen; ( function () { function matches( el, sel ) { return !! ( el.matches && el.matches( sel ) || el.msMatchesSelector && el.msMatchesSelector( sel ) ); } document.body.addEventListener( 'click', function ( event ) { if ( ! event.target ) { return; } var el; if ( matches( event.target, 'a.share-x' ) ) { el = event.target; } else if ( event.target.parentNode && matches( event.target.parentNode, 'a.share-x' ) ) { el = event.target.parentNode; } if ( el ) { event.preventDefault(); // If there's another sharing window open, close it. if ( typeof windowOpen !== 'undefined' ) { windowOpen.close(); } windowOpen = window.open( el.getAttribute( 'href' ), 'wpcomx', 'menubar=1,resizable=1,width=600,height=350' ); return false; } } ); } )();