score:0

Accepted answer

The original data in the bl.ocks that you used as example (this one, your link is broken) looks like this:

State,Under 5 Years,5 to 13 Years,14 to 17 Years,18 to 24 Years,25 to 44 Years,45 to 64 Years,65 Years and Over
AL,310504,552339,259034,450818,1231572,1215966,641667
AK,52083,85640,42153,74257,198724,183159,50277
AZ,515910,828669,362642,601943,1804762,1523681,862573
AR,202070,343207,157204,264160,754420,727124,407205
CA,2704659,4499890,2159981,3853788,10604510,8819342,4114496

So, let's see how we can replicate that row function:

The main problem with your attempt is that, unlike the original row function, you're not iterating through each object in the data array. When you do this...

data.total = t;

... you're just setting a property in that array, which is not what you want.

So, you have to iterate through each object in the array. For instance, using Array.prototype.forEach:

function type(data) {
  data.columns = Object.keys(data[0]);
  data.forEach(function(d) {
    for (i = 1, t = 0; i < data.columns.length; ++i) t += d[data.columns[i]] = +d[data.columns[i]];
    d.total = t;
  });
  return data;
};

Here is the demo:

var csv = `State,Under 5 Years,5 to 13 Years,14 to 17 Years,18 to 24 Years,25 to 44 Years,45 to 64 Years,65 Years and Over
AL,310504,552339,259034,450818,1231572,1215966,641667
AK,52083,85640,42153,74257,198724,183159,50277
AZ,515910,828669,362642,601943,1804762,1523681,862573
AR,202070,343207,157204,264160,754420,727124,407205
CA,2704659,4499890,2159981,3853788,10604510,8819342,4114496`;

const data = d3.csvParse(csv);

var tmp_data = type(data);

console.log(tmp_data)

function type(data) {
  data.columns = Object.keys(data[0]);
  data.forEach(function(d) {
    for (i = 1, t = 0; i < data.columns.length; ++i) t += d[data.columns[i]] = +d[data.columns[i]];
    d.total = t;
  });
  return data;
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>


Related Query