Substitute random items in a JavaScript array?

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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
raja
Updated on 09-Nov-2020 08:09:22

Advertisements