Explain Codes LogoExplain Codes Logo

How to get a number of random elements from an array?

javascript
random-elements
array-shuffling
lodash
Alex KataevbyAlex Kataev·Dec 6, 2024
TLDR

Obtain random elements from an array by shuffling it using the Fisher-Yates algorithm and slicing the desired number of elements:

function getRandomElements(arr, n) { let w = arr.length, t, i; // Fisher-Yates Shuffle. Remember: “Randomizer, randomize!” while (w) { i = Math.floor(Math.random() * w--); t = arr[w]; arr[w] = arr[i]; arr[i] = t; } // We’re taking the first n elements as lightly as a slice of pizza... return arr.slice(0, n); } // Usage: const randomItems = getRandomElements([1, 2, 3, 4, 5, 6], 3); console.log(randomItems); // Example: [4, 1, 5]

Remember to shuffle only up to the point necessary (up to n) and don’t exceed the array's length to avoid awkwardly dragging around undefined items.

Efficient shuffling for large arrays

An extremely shuffled array might seem fun, but with large data sets, it's less of a party and more of a performance crisis. Instead, consider a tailored shuffling up to the nth element only:

function efficientRandomElements(arr, count) { let result = new Array(count), len = arr.length, taken = new Array(len); if (count > len) throw new RangeError("efficientRandomElements: more elements taken than available"); // Like a novice hoverboarder, we’re randomly tumbling toward len. while (count--) { let x = Math.floor(Math.random() * len); result[count] = arr[x in taken ? taken[x] : x]; taken[x] = --len in taken ? taken[len] : len; } return result; }

Shorter code with lodash

If brevity is your game and lodash is your flame, it can provide a simple way to play:

// Using lodash, more like low-dash am I right? Okay, I'll see myself out... const _ = require('lodash'); let randomElems = _.sampleSize([1, 2, 3, 4, 5, 6], 3);

Guarantee no duplicated elements

Fancy a bouquet of unique flowers and not a single petal repeated? A set or lodash's _.sampleSize are your gardeners ensuring unique selections. Let's dig into it:

function uniqueFlowers(arr, n) { let resultSet = new Set(); // Keep picking new flowers until our bouquet has n types. while (resultSet.size < n) { resultSet.add(arr[Math.floor(Math.random() * arr.length)]); } return Array.from(resultSet); } // Or take an eco-friendly shortcut with lodash: let uniqueBlooms = _.sampleSize([1, 2, 3, 4, 5, 6], 3);

Manage over-fetching elements

Since we can't just summon elements out of thin air, be cautious with cases where your client asks for more elements than you have in your array. Your function could either return 'As many as we got, buddy', or slam the client with a dazzling error display:

function cautionaryTale(arr, n) { if( n > arr.length ) { console.warn("Requested more elements than unicorns exist, providing all available ones."); return arr; } return getRandomElements(arr, n); }

Fair results in high-performance scenarios

For sessions dealing with large arrays or requiring high performance, a minimal shuffling strategy might be more suitable. It's like asking your shuffle routine to save its energy for the race. Also, ensure that you're dealing a fair hand by maintaining unbiased randomization.