Substitute random items in a JavaScript array?


To substitute random items with items from an array with different ones in JavaScript. Let’s look at the instance; the array is −

Var array=[m,n,o,p]

Let's choose two random items to be replaced with a, while the others remain in their original positions. If m and n are the randomly selected items, and one is removed on one instance, the array would be −

Changed array=[a,a,o,p]

Let’s dive into the article to learn more about substituting random items in a JavaScript array. To substitute random items, use random() along with map().

Using random() method

The JavaScript method random() is used to return a pseudo-random or random number that falls inside a specified range. The random() function must be called through the placeholder object Math because it is a static function of the Math object.

Syntax

Following is the syntax for random()

Math.random();

Using map()

The map() method builds a new array from the contents of the calling array after performing a given function on each element.

Syntax

Following is the syntax for map()

array.map(function(currentValue, index, arr), thisValue)

For getting more understanding on substituting a random item in a JavaScript let’s look into the following examples.

Example

In the following example we are running the script to substitute the random item in the JavaScript array.

<!DOCTYPE html>
<html>
   <body>
      <script>
         function randomone(array, count) {
            return function() {
               const indices = new Set();
               do {
                  indices.add(Math.floor(Math.random() * array.length));
               } while (indices.size < count)
               return array.map((v, i) => indices.has(i) ? 1 : v);
            };
         }
         var myArray = ['A', 'B', 'C', 'D'],
         newarray = randomone(myArray, 2);
         document.write(...newarray());
      </script>
   </body>
</html>

When the script gets executed, it will generate an output consisting of an array with a value of "1" substituted randomly in between the array items. This will get changed whenever the user executes the script.

Example

Consider the following example, here we are running the script to get unique random indexes and running a loop over the indexes and making them equal to 2.

<!DOCTYPE html>
<html>
   <body>
      <script>
         var my_arr = ["ab", "bc", "cd", "de"];
         const random = (num, count) => {
            const set = new Set();
            while (set.size < count) {
               set.add(Math.floor(Math.random() * num));
            }
            return [...set];
         };
         const alter = (arr, count = 2) => {
            const output = [...arr];
            random(arr.length, count).forEach((index) => (output[index] = 2));
            return output;
         };
         document.write(JSON.stringify(alter(my_arr)));
      </script>
   </body>
</html>

On running the above script, the output window will pop up, displaying the array generated with a value of "2" substituted randomly in the array by the event that triggers the script.

Example

Execute the below script to observe how to substitute random item in a JavaScript array.

<!DOCTYPE html>
<html>
   <body>
      <script>
         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);
         document.write(...result() + " < br > ");
      </script>
   </body>
</html>

hen the script gets executed, the event gets triggered and displays an array with a randomly substituted value in the indexes, and it will keep changing whenever the user executes the script.

Updated on: 21-Apr-2023

209 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements