- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Function to choose elements randomly in JavaScript
Suppose we have an array of literals that contains no duplicate elements like this −
const arr = [2, 5, 4, 45, 32, 46, 78, 87, 98, 56, 23, 12];
We are required to write a JavaScript function that takes in an array of unique literals and a number n. The function should return an array of n elements all chosen randomly from the input array and no element should appear more than once in the output array.
Therefore, let’s write the code for this function −
Example
The code for this will be −
const arr = [2, 5, 4, 45, 32, 46, 78, 87, 98, 56, 23, 12]; const chooseRandom = (arr, num = 1) => { const res = []; for(let i = 0; i < num; ){ const random = Math.floor(Math.random() * arr.length); if(res.indexOf(arr[random]) !== -1){ continue; }; res.push(arr[random]); i++; }; return res; }; console.log(chooseRandom(arr, 4));
Output
The output in the console will be −
[ 5, 2, 4, 78 ]
- Related Articles
- Changing color randomly in JavaScript
- Picking index randomly from array in JavaScript
- Currified function that multiples array elements in JavaScript
- Randomly shuffling an array of literals in JavaScript
- How to exclude certain values from randomly generated array JavaScript
- Function for counting frequency of space separated elements in JavaScript
- Is there a DOM function which deletes all elements between two elements in JavaScript?
- How to remove elements from an array until the passed function returns true in JavaScript?
- HTML5 Audio to Play Randomly
- How to randomly assign participants to groups in R?
- How to play HTML5 Audio Randomly
- Assigning function to variable in JavaScript?
- How to choose a background color through a color picker in JavaScript?
- How to randomly select element from range in Python?
- Function returning another function in JavaScript

Advertisements