

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
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 Questions & Answers
- Substitute tokens in a String in Java
- Select random values from an array in JavaScript?
- How to shuffle an array in a random manner in JavaScript?
- JavaScript - find distance between items on array
- JavaScript Random
- 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
- Clearing items in a nested MongoDB array?
- Sort an array to have specific items first in the array - JavaScript
- Add property to common items in array and array of objects - JavaScript?
- JavaScript - How to pick random elements from an array?
- How to find distance between items on array JavaScript
- Generate a random array of integers in Java
Advertisements