I want to create a multiple-line chart in d3.js, the data is in csv and is organized as follows:
¦Date ¦ Cat A¦ Cat B¦ Cat C¦
¦:---------¦:----:¦:----:¦-----:¦
¦2019-12-01¦2 ¦6 ¦9 ¦
¦2018-11-02¦4 ¦4 ¦20 ¦
How do I read the data to be arranged into three columns:
¦Date ¦ Category¦ value ¦
¦:---------¦:-------:¦------:¦
¦2019-12-01¦CAT A ¦2 ¦
¦2018-11-02¦CAT A ¦4 ¦
¦2019-12-01¦CAT B ¦6 ¦
¦2018-11-02¦CAT B ¦9 ¦
Please note that I would like to ignore one of the columns (CAT C)
CodePudding user response:
Typically in D3, one imports flattened data and then groups or nests it accordingly. This means (as far as I'm aware) the tools for doing the reverse aren't quite so natural. In this case it may be straightforward and readable to use vanilla Javascript:
const data = [
{ Date: '2019-12-01', 'A' : 2, 'B' : 6, 'C' : 9 },
{ Date: '2018-11-02', 'A' : 4, 'B' : 4, 'C' : 20 }
];
console.log(data)
result = [];
data.forEach(row => {
let a = (({ Date, A, B, C }) => ({ Date, A}))(row);
result.push(a)
let b = (({ Date, A, B, C }) => ({ Date, B}))(row);
result.push(b)
});
console.log(result);