Thursday, October 16, 2025
HomeLanguagesJavascriptD3.js | d3.sum() function

D3.js | d3.sum() function

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

Syntax:

d3.sum(Array)

Parameters: This function accepts a parameters Array which is an array of elements whose sum are to be calculated.

Return Value: It returns the sum of the given array’s element.

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

Example 1:




<html>
  
<head>
    <title>
      Getting sum 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
        var Array1 = [10, 20, 30, 40, 50, 60];
        var Array2 = [1, 2];
        var Array3 = [0, 1.5, 6.8];
        var Array4 = [.8, .08, .008];
  
        // Calling to d3.sum() function
        A = d3.sum(Array1);
        B = d3.sum(Array2);
        C = d3.sum(Array3);
        D = d3.sum(Array4);
  
        // Getting sum 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:

210
3
8.3
0.888

Example 2:




<html>
  
<head>
    <title>
      Getting sum 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
        var Array1 = [];
        var Array2 = ["a", "b", "c"];
        var Array3 = [1, "B", "C"];
        var Array4 = ["Geek", "Geeks", 2, 3, "neveropen"];
  
        // Calling to d3.sum() function
        A = d3.sum(Array1);
        B = d3.sum(Array2);
        C = d3.sum(Array3);
        D = d3.sum(Array4);
  
        // Getting sum 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:

0
0
1
5

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

Ref: https://devdocs.io/d3~4/d3-array#sum

RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS