Andrew Kilburn
Andrew Kilburn

Reputation: 2251

How to use forEach in d3 using Javascript

I'm trying to make a pie chart using d3. To do this I am send my data in a JSON format to my view and then I'd like to try and total up three of the parameters and then use these in the pie chart. So far I have managed to get the data to the view but now I need to use a foreach to total up the parameters. I'm only working on one at the moment.

Script:

   var width = 960,
    height = 500,
    radius = Math.min(width, height) / 2;

        var color = d3.scale.ordinal()
            .range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c"]);

        var arc = d3.svg.arc()
            .outerRadius(radius - 10)
            .innerRadius(0);

        var pie = d3.layout.pie()
            .sort(null)
            .value(function (d) { return d.Query; });

        var svg = d3.select("body").append("svg")
            .attr("width", width)
            .attr("height", height)
          .append("g")
            .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

        var data = @Html.Raw(@Model.output);

        var QueryTotal = data.forEach(function(d) {
            d.Query = +d.Query;
        });

        console.log(QueryTotal);

            var g = svg.selectAll(".arc")
                .data(pie(data))
              .enter().append("g")
                .attr("class", "arc");

            g.append("path")
                .attr("d", arc)
                .style("fill", function (d) { return color("Query"); });

            g.append("text")
                .attr("transform", function (d) { return "translate(" + arc.centroid(d) + ")"; })
                .attr("dy", ".35em")
                .style("text-anchor", "middle")
            .text(function (d) { return "Query"; });

How do I use a for each to total up the values, I've given it an attempt which you can see above. It just returns undefined.

Upvotes: 0

Views: 1944

Answers (2)

Lars Kotthoff
Lars Kotthoff

Reputation: 109242

The D3 way to do this is to use d3.sum():

var QueryTotal = d3.sum(data, function(d) { return d.Query; });

Upvotes: 1

Andrei Nemes
Andrei Nemes

Reputation: 3122

To sum the values, use reduce()

var QueryTotal = data.reduce(function(prev, d) {
    return prev + d.Query;
}, 0);

Or, using your existing structure:

var QueryTotal = 0;

data.forEach(function(d) {
    QueryTotal += d.Query;
});

Upvotes: 1

Related Questions