Skip to content

Instantly share code, notes, and snippets.

View rameshbaskar's full-sized avatar

Ramesh Baskarasubramanian rameshbaskar

View GitHub Profile
@rameshbaskar
rameshbaskar / getRandomItemsFromArray.js
Created March 8, 2023 06:43
Get random items from array
function getRandomItemsFromArray(sourceArray, numOfItems) {
if (numOfItems > sourceArray.length) {
throw new Error('Trying to get more items than the array length!!!');
}
const shuffledArray = sourceArray.concat().sort((() => Math.random() - 0.5);
return shuffledArray.slice(0, (numOfItems - 1));
}
// The concat() function returns a copy of the sourceArray so that the original array is not modified.