
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Pick Random Elements from an Array 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.
Example
Following is the code −
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
This will produce the following output in console −
[ 5, 2, 4, 78 ]
Advertisements