Open In App

D3.js | d3.shuffle() function

The d3.shuffle() function in D3.js is used to randomize or shuffle the order of the given array elements in place and returns the array.

Syntax:



d3.shuffle( Array, start, stop )

Parameters: This function accepts three parameters as mentioned above and described below:

Return Value: It returns the array of shuffled elements.



Below programs illustrate the d3.shuffle() function in D3.js:

Example 1:




<!DOCTYPE html>
<html>
  
<head>
    <title>d3.shuffle() Function</title>
      
    <script src='https://d3js.org/d3.v4.min.js'></script>
</head>
  
<body>
    <script>
       
        // Initialising some array of elements
        Array1 = [1, 2, 3, 4];
        Array2 = [10, 20, 30, 40];
        Array3 = [5, 7, 9, 11];
        Array4 = [2, 4, 6, 8, 10];
           
        // Calling to d3.shuffle() function
        A = d3.shuffle(Array1);
        B = d3.shuffle(Array2, 1, 3);
        C = d3.shuffle(Array3);
        D = d3.shuffle(Array4, 2, 5);
           
        // Getting the shuffled elements
        document.write(A + "<br>");
        document.write(B + "<br>");
        document.write(C + "<br>");
        document.write(D + "<br>");
    </script>
</body>
  
</html>

Output:

2, 3, 1, 4
20, 40, 10, 30
11, 9, 5, 7
2, 10, 4, 8, 6

Example 2:




<!DOCTYPE html>
<html>
  
<head>
    <title>d3.shuffle() Function</title>
      
    <script src='https://d3js.org/d3.v4.min.js'></script>
</head>
  
<body>
    <script>
       
        // Initialising some array of elements
        Array1 = ["a", "b", "c"];
        Array2 = ["z", "y", "x"];
           
        // Calling to d3.shuffle() function
        A = d3.shuffle(Array1);
        B = d3.shuffle(Array2);
           
        // Getting the shuffled elements
        document.write(A + "<br>");
        document.write(B + "<br>");
    </script>
</body>
  
</html>

Output:

b, a, c
z, y, x

Reference: https://devdocs.io/d3~5/d3-array#shuffle


Article Tags :