Substitute random items in a JavaScript array?

To substitute random items, use random() along with map().


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, counter) => index.has(counter) ? 'Adam' : value);
var names = ['John', 'David', 'Bob', 'Mike', 'Carol', 'Sam'],
   result = substituteRandomValue(names, 2);

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo278.js.


This will produce the following output on console −

PS C:\Users\Amit\javascript-code> node demo278.js
John David Bob Adam Carol Adam