Skip to content

Instantly share code, notes, and snippets.

@rameshbaskar
Created March 8, 2023 06:43
Show Gist options
  • Select an option

  • Save rameshbaskar/5af924d67b5e2d6c3f5a042e03b13a59 to your computer and use it in GitHub Desktop.

Select an option

Save rameshbaskar/5af924d67b5e2d6c3f5a042e03b13a59 to your computer and use it in GitHub Desktop.

Revisions

  1. rameshbaskar created this gist Mar 8, 2023.
    9 changes: 9 additions & 0 deletions getRandomItemsFromArray.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,9 @@
    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.