kboyd
kboyd

Reputation: 23

Creating array from csv with d3.group without group headers

I am trying to replicate the example here by Nadieh Bremer which is a radar chart made in D3.js.

The data structure which is used in Nadieh's example is:

var data = [
  [//iPhone
    {axis:"Battery Life",value:20},
    {axis:"Brand",value:28},
    {axis:"Contract Cost",value:29},
    {axis:"Design And Quality",value:17},
    {axis:"Have Internet Connectivity",value:22},
    {axis:"Large Screen",value:02},
    {axis:"Price Of Device",value:21},
    {axis:"To Be A Smartphone",value:50}            
  ],[//Samsung
    {axis:"Battery Life",value:27},
    {axis:"Brand",value:16},
    {axis:"Contract Cost",value:35},
    {axis:"Design And Quality",value:13},
    {axis:"Have Internet Connectivity",value:20},
    {axis:"Large Screen",value:13},
    {axis:"Price Of Device",value:35},
    {axis:"To Be A Smartphone",value:38}
  ],etc.
];

I want to bring in the data from a CSV file which is set-up like this:

axis,value,type
Battery Life,20,iPhone
Brand,28,iPhone
Contract Cost,29,iPhone
Design And Quality,17,iPhone
Have Internet Connectivity,22,iPhone
Large Screen,02,iPhone
Price Of Device,21,iPhone
To Be A Smartphone,50,iPhone    
Battery Life,27,SAmsung
Brand,16,SAmsung
...etc.

In my script, I have:

var tmpArr;
    d3.csv("data1.csv", (d) => {
    tmp = d;
    tmpArr = Array.from(d3.group(tmp, d => d.group));
    console.log(tmpArr);
});

This obviously returns an array for each group with the title of the group as the first element of the array and then the contents of the group as the second element in the array.

I would be grateful for help to remove that first element so that I'm simply returned an array of the values I need. I'm pretty sure I need to use d3.map() but I just can't quite work out what to do with it. Thanks in advance.

Upvotes: 1

Views: 159

Answers (1)

Robin Mackenzie
Robin Mackenzie

Reputation: 19289

You can just use a standard .map and for every pair returned from Array.from(d3.group(...)) return the 2nd item of that pair. For the 2nd item in each pair use index [1] because arrays are zero-based indices.

The working example aligns to the data structure in Nadieh Bremer's block:

const csv = `axis,value,type
Battery Life,20,iPhone
Brand,28,iPhone
Contract Cost,29,iPhone
Design And Quality,17,iPhone
Have Internet Connectivity,22,iPhone
Large Screen,02,iPhone
Price Of Device,21,iPhone
To Be A Smartphone,50,iPhone
Battery Life,27,SAmsung
Brand,16,SAmsung
Contract Cost,24,SAmsung
Design And Quality,14,SAmsung
Have Internet Connectivity,22,SAmsung
Large Screen,05,SAmsung
Price Of Device,15,SAmsung
To Be A Smartphone,48,SAmsung
`;

const data = d3.csvParse(csv);

const grouped = Array.from(d3.group(data, d => d.type));

const arrForViz = grouped.map(g => g[1]);

console.log(arrForViz);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/6.7.0/d3.min.js"></script>

Upvotes: 1

Related Questions