I am trying to get the basic grasp of parsing a CSV file with node js.
I wrote a simple function to get the last character (in my case it is always a number) of every string in an array and show me the biggest number:
var ARRAY_OF_ALL_EMAILS = [email_1, email_22]
function GET_NUMBER() {
let MAXIMAL_NUMBER;
for (let i = 0; i < ARRAY_OF_ALL_EMAILS.length; i += 1) {
if (MAXIMAL_NUMBER == null || MAXIMAL_NUMBER == undefined || MAXIMAL_NUMBER < (ARRAY_OF_ALL_EMAILS[i].slice(-1))) {
MAXIMAL_NUMBER = (ARRAY_OF_ALL_EMAILS[i].slice(-1))
}
}
return MAXIMAL_NUMBER;
}
let MAXIMAL_NUMBER_FINAL = GET_NUMBER();
console.log(MAXIMAL_NUMBER_FINAL);
this piece of code works as expected:
> node index.js
> 2
However what I am trying to do know is to parse a csv file and extract only col2 of this file and store the values in my variable var ARRAY_OF_ALL_EMAILS;
so it behaves as if I declared the array this way: var ARRAY_OF_ALL_EMAILS = [email_1, email_2]
.
I manage to successfully parse the whole csv file, but when I am trying to use only a certain column I always fail.
Could you please show me how to use only a certain column from a CSV file and store it as an array so I can use it in my GET_NUMBER
function? I know it should be possible by either index or name, but it just simply does not work for me.
Example of the csv:
col1,col2,col3,col4
aaa1,aaa_1,aaa3,aaa4
bbb1,bbb_2,bbb3,bbb4
ccc1,ccc_3,ccc3,ccc4
For this I am using a csv package (npm install csv
)
Thanks
Edit
With Barkaas help I have this:
const parse = require('csv-parse/lib/sync'); //include
const fs = require(fs);
//loading data from the file
var global_data = fs.readFileSync(data.csv).toString();
//the dataset
const input = global_data;
//calling the npm package and save to records
const records = parse(input, {
columns: true,
skip_empty_lines: true
});
//map the output from csv-parse to the column
const column_two = records.map(rec => rec[col2]);
//assing the values to another variable used in my function
var ARRAY_OF_ALL_EMAILS = column_two//[aaa_1, bbb_4444444, ccc_3333333]
//function to return the highest number in every string
function GET_NUMBER() {
let MAXIMAL_NUMBER;
for (let i = 0; i < ARRAY_OF_ALL_EMAILS.length; i += 1) {
let n = ARRAY_OF_ALL_EMAILS[i].lastIndexOf('_');
let result = ARRAY_OF_ALL_EMAILS[i].substring(n + 1);
if (MAXIMAL_NUMBER == null || MAXIMAL_NUMBER == undefined || MAXIMAL_NUMBER < result) {
MAXIMAL_NUMBER = result
}
}
return MAXIMAL_NUMBER;
}
//print the highest number from every string
let MAXIMAL_NUMBER_FINAL = GET_NUMBER();
console.log(MAXIMAL_NUMBER_FINAL);
This works for me.