Skip to content
the poor coder

get n random items from array javascript

Poor Man
Published
Reading time
2 min read
On this page

Get n random items from array in JavaScript#

If you have an array in JavaScript and want to get n random items from it, there are several ways to do it:

Method 1: Using a for loop and Math.random()#

This method involves using a for loop to iterate n times and Math.random() to generate a random index within the array. The selected items are then pushed into a new array.

Text

function getRandomItems(array, n) {
  let result = [];
  for (let i = 0; i < n; i++) {
    let randomIndex = Math.floor(Math.random() * array.length);
    result.push(array[randomIndex]);
  }
  return result;
}

// Example usage
let myArray = [1, 2, 3, 4, 5];
let randomItems = getRandomItems(myArray, 3);
console.log(randomItems); // Outputs 3 random items from the array

Method 2: Using the Fisher-Yates shuffle algorithm#

This method involves shuffling the array using the Fisher-Yates shuffle algorithm, and then selecting the first n items from the shuffled array.

Text

function shuffleArray(array) {
  for (let i = array.length - 1; i > 0; i--) {
    let j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }
  return array;
}

function getRandomItems(array, n) {
  let shuffledArray = shuffleArray(array);
  return shuffledArray.slice(0, n);
}

// Example usage
let myArray = [1, 2, 3, 4, 5];
let randomItems = getRandomItems(myArray, 3);
console.log(randomItems); // Outputs 3 random items from the array

Method 3: Using the lodash library#

The lodash library provides a convenient way to get n random items from an array. The sampleSize function takes an array and a number as arguments, and returns a new array with n randomly selected items from the original array.

Text

const _ = require('lodash');

function getRandomItems(array, n) {
  return _.sampleSize(array, n);
}

// Example usage
let myArray = [1, 2, 3, 4, 5];
let randomItems = getRandomItems(myArray, 3);
console.log(randomItems); // Outputs 3 random items from the array

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC