Home > Net >  How to filter data ingested from a CSV file by column
How to filter data ingested from a CSV file by column

Time:12-05

I have data in a CSV file that looks like this:

Year      Teams     Matches    Goals
2014      32        64         171
2010      32        64         125
2006      32        64         147
2002      32        64         161
1998      32        64         171
1994      24        52         141

enter image description here

I ingest the data using the following code:

let promises = [
    d3.csv('data/test-data.csv', d3.autoType),
];

Promise.all(promises)
    .then(function (data) {
        createVis(data)
    })
    .catch(function (err) {
        console.log(err)
    });

Then, I have a function createVis() that wrangles the data and creates a graph:

function createVis(data) {

    let graphData = data[0]

    wrangleData()

}

In my use case, the wrangleData() function would only grab the Year and Matches columns of the original data set.

Something like this:

function wrangleData(data) {

let filteredData = []

filteredData = data.filter...

}

filterdData would look like this:

Year      Matches   
2014      64        
2010      64        
2006      64        
2002      64        
1998      64        
1994      52        

How would I do this?

Thanks!

CodePudding user response:

To reduce the amount of keys in the objects, use map() with object destructuring to return an object with the desired keys:

const data = [
  { Year: '2001', Teams: '32', Matches: '64', Goals: '161' },
  { Year: '2011', Teams: '53', Matches: '33', Goals: '111' }
];

const res = data.map(({ Year, Matches }) => ({ Year, Matches }));
console.log(res)

  • Related