- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Substitute random items in a JavaScript array?
To substitute random items, use random() along with map().
Example
Following is the code −
function substituteRandomValue(names, size) { return function () { const index = new Set(); do { index.add(Math.floor(Math.random() * names.length)); } while (index.size < size) return names.map((value, counter) => index.has(counter) ? 'Adam' : value); }; } var names = ['John', 'David', 'Bob', 'Mike', 'Carol', 'Sam'], result = substituteRandomValue(names, 2); console.log(...result());
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo278.js.
Output
This will produce the following output on console −
PS C:\Users\Amit\javascript-code> node demo278.js John David Bob Adam Carol Adam
- Related Articles
- How to shuffle an array in a random manner in JavaScript?
- Select random values from an array in JavaScript?
- JavaScript - find distance between items on array
- Completely removing duplicate items from an array in JavaScript
- Find the least duplicate items in an array JavaScript
- Split Array of items into N Arrays in JavaScript
- Remove duplicate items from an array with a custom function in JavaScript
- Sort an array to have specific items first in the array - JavaScript
- Add property to common items in array and array of objects - JavaScript?
- Substitute tokens in a String in Java
- How to find distance between items on array JavaScript
- JavaScript function that should count all unique items in an array
- Algorithm to get the combinations of all items in array JavaScript
- Grouping an Array and Counting items creating new array based on Groups in JavaScript
- JavaScript - How to pick random elements from an array?

Advertisements