Substitute random items in a JavaScript array?

To substitute random items in a JavaScript array, you can use Math.random() along with map() to replace selected elements with new values while keeping others in their original positions.

For example, if you have an array [m, n, o, p] and want to replace two random items with 'a', the result might be [a, a, o, p] where m and n were randomly selected and replaced.

Using Math.random() Method

The Math.random() method returns a pseudo-random number between 0 (inclusive) and 1 (exclusive). It's used to generate random indices for array element selection.

Syntax

Math.random();

Using map() Method

The map() method creates a new array by calling a function on each element of the original array, making it perfect for conditional replacements.

Syntax

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

Example 1: Replace Random Items with Number

This example demonstrates substituting random array elements with the value 1:

<!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>
1,B,1,D

Example 2: Using Set for Unique Random Indices

This approach generates unique random indices and replaces those positions with the value 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>
["ab",2,"cd",2]

Example 3: Replace with String Values

This example shows substituting random array elements with a specific string value:

<!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>
Adam,David,Adam,Mike,Carol,Sam

How It Works

The process involves three key steps:

  • Generate unique random indices using Math.random() and a Set to avoid duplicates
  • Use map() to iterate through the original array
  • Replace elements conditionally based on whether their index is in the random indices set

Conclusion

Substituting random items in JavaScript arrays is efficiently achieved using Math.random() for index generation, Set for uniqueness, and map() for conditional replacement. This approach ensures original array integrity while providing flexible random substitution.

Updated on: 2026-03-15T23:19:00+05:30

462 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements