Open In App

D3.js d3.mean() function

Last Updated : 10 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The d3.mean() function in D3.js is used to return the mean or average of the given array’s elements. If the array is empty then it returns undefined.

Syntax:

d3.mean(Array)

Parameters:

This function accepts a parameter Array which is an array of elements whose mean are to be calculated. Here elements should be integers not strings otherwise it returns undefined.

Return Value:

It returns the mean or average of the given array’s element.

Example 1: This example shows the use of mean() function.

HTML
<!DOCTYPE html>
<html>

<head>
    <title>
        Getting mean of the
        elements of given array
    </title>
</head>

<body>
    <script src='https://d3js.org/d3.v4.min.js'>
    </script>

    <script>
        // initialising the array of elements
        let Array1 = [10, 20, 30, 40, 50, 60];
        let Array2 = [1, 2];
        let Array3 = [0, 1.5, 6.8];
        let Array4 = [.8, .08, .008];

        // Calling to d3.mean() function
        A = d3.mean(Array1);
        B = d3.mean(Array2);
        C = d3.mean(Array3);
        D = d3.mean(Array4);

        // Getting mean of the given array's element
        document.write(A + "<br>");
        document.write(B + "<br>");
        document.write(C + "<br>");
        document.write(D + "<br>");
    </script>
</body>

</html>

Output:

35
1.5
2.766666666666667
0.296

Example 2: This example shows the use of mean() function.

HTML
<!DOCTYPE html>
<html>

<head>
    <title>
        Getting mean of the
        elements of given array
    </title>
</head>

<body>
    <script src='https://d3js.org/d3.v4.min.js'>
    </script>

    <script>
        // initialising the array of elements
        let Array1 = [];
        let Array2 = ["a", "b", "c"];
        let Array3 = [1, "B", "C"];
        let Array4 = ["Geek", "Geeks", 2, 3, "GeeksforGeeks"];

        // Calling to d3.mean() function
        A = d3.mean(Array1);
        B = d3.mean(Array2);
        C = d3.mean(Array3);
        D = d3.mean(Array4);

        // Getting mean of the given array's element
        document.write(A + "<br>");
        document.write(B + "<br>");
        document.write(C + "<br>");
        document.write(D + "<br>");
    </script>
</body>

</html>

Output:

undefined
undefined
1
2.5

Note: In the above output, if the parameter is empty or strings then it returns undefined and if the parameter is string including some integers value then the mean of the integer’s value is returned.



Next Article

Similar Reads