- 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
How to exclude certain values from randomly generated array JavaScript
We have to create a function that takes in 2 arguments: an integer and an array of integers. First argument denotes the length of array we have to return and the second argument contains the elements that should not be present in our return array. Actually, we need an array of random numbers between 0 to 100 but it should not include any element that’s present in the argument array.
Note − No two numbers should be duplicate.
Let’s call our function generateRandom(). The code for this would be −
Example
const absentArray = [44, 65, 5, 34, 87, 42, 8, 76, 21, 33]; const len = 10; const generateRandom = (len, absentArray) => { const randomArray = []; for(let i = 0; i < len; ){ const random = Math.floor(Math.random() * 100); if(!absentArray.includes(random) && !randomArray.includes(random)){ randomArray.push(random); i++; } }; return randomArray; } console.log(generateRandom(len, absentArray));
Output
Output in the console will be −
[ 23, 93, 29, 25, 37, 63, 54, 11, 69, 79 ]
Advertisements