# get n random items from array javascript

## 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.


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.


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.


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