0

I've used the 'fast-csv' module to parse the csv file for other manipulations, but that returns data row-wise. I want to read the first 2 columns of a csv file. Can someone please help?

0

1 Answer 1

1

I see two options.

One is do specify which headers you want in fast-csv and discard the rest. This approach will return an object which may suit your needs or you can then turn that into an array afterwards.

const csv = require('fast-csv')

const CSV_STRING = 'a,b,c\n' +
                     'a1,b1,c1\n' +
                     'a2,b2,c2\n'

let filtered = []
csv
  .fromString(CSV_STRING, { headers: ['column_1', 'column_2'], renameHeaders: true, discardUnmappedColumns: true }) // I give arbitrary names to the first two columns - use whatever make sense
  // .fromString(CSV_STRING, { headers: ['column_1', undefined, 'column_3'], discardUnmappedColumns: true }) // I could use undefined if I wanted to say skip column 2 and just want 1 and 3
  .on('data', function (data) {
    // console.log([data.column_1, data.column_2])
    filtered.push([data.column_1, data.column_2]) // or you can push to an array
  })
  .on('end', function () {
    console.log('done')
    console.log(filtered)
  })

The other is to return as an array (default) and filter what you need using the transform method

const csv = require('fast-csv')

const CSV_STRING = 'a,b,c\n' +
                     'a1,b1,c1\n' +
                     'a2,b2,c2\n'

csv
  .fromString(CSV_STRING)
  .transform(function (data) {
    return [data[0], data[1]]
  })
  .on('data', function (data) {
    console.log(data)
  })
  .on('end', function () {
    console.log('done')
  })
Sign up to request clarification or add additional context in comments.

5 Comments

thanks I used the second option and it works perfectly!
how can I skip the first row (header)?
@Ann I've updated the first example to 1) remove the first row and 2) push to an array
Thanks. That works! But I didnt understand why and how it works. when I set header: true it doesnt work though. Can you give me some explanation in what's going on here?
You should be able to use headers:true but in that case your fields will have a different name (the name of the actual headers instead of the ones I created called 'column_1' and 'column_2''. Inspect your data in the on callback to see what it looks like. Also remove the renameHeaders: true option.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.