Sum an entire csv column to show total with d3 javascript

I have the following local csv file:

country,population,porcentage
China,15,1.1
India,86,4.1
United States,357,15.2
Indonesia,1207,51.2
Brazil,717,29.12

What I'm trying to do is to get the total value of population column in order to show it below my bar chart. I'm using d3 csv function to work with the data but the problem is that when I get the data the function is putting it in separate objects which is not allow me to add them up. This is how they look.

Link

I have tried first with reduce but it doesn't work.

import { csv, sum } from 'd3';

csv("./src/bardata.csv", (() => {
    var sum;
    return sum = (...args) => {
        return args.reduce((a, b) => a + b, 0);
    };
}))();

I have also tried using map function but my understanding is that this only works with arrays and my data is in separate objects. Anyway, I keep recieving "data.map is not a function " error. Any suggestions?

Upvotes: 1

Views: 1292

Answers (2)

altocumulus
altocumulus

Reputation: 21578

You already imported d3.sum() which can be used to sum an array of objects by providing an accessor function as the second argument:

d3.sum(iterable[, accessor])

Returns the sum of the given iterable of numbers. If the iterable contains no numbers, returns 0. An optional accessor function may be specified, which is equivalent to calling Array.from before computing the sum.

For your code this could be something along the following lines

import { csv, sum } from 'd3';

csv("./src/bardata.csv")
  .then(data => {
    const total = sum(data, d => d.population);
  });

Upvotes: 1

Jasdeep Singh
Jasdeep Singh

Reputation: 8301

Please try to use it as below:

import { csv, sum } from 'd3';

csv("./src/bardata.csv", (data) => {
    const result = sum(data, function(d) { return +d.population; })
});

Upvotes: 0

Related Questions