Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

85
Vistas
Adding Numbers from csv

I am trying to add all numbers from an column to an variable. The Problem is my code is adding the String to which results into NaN.

var csvData=[];
    let test = 0;
    var parser = parse({delimiter: ','}, function(err, data){
    });

    fs.createReadStream(__dirname+'/test2.csv','utf16le').pipe(parser)
        .on('data', function(csvrow) {
            csvData.push(csvrow);
            test = test + (csvrow[2]);
        })
        .on('end',function() {
            console.log(test)
        });

gives me : "0Daily Device Installs00001000101100" and if I add parseInt(csvrow[2]) I will get NaN for test.

My goal is to add all numbers after Daily Device Installs, what am I missing?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

I did a bit research on Node.js CSV package.

Use the header

If your CSV file contains a header row as supposed in comment by GrafiCode, like in this example:

"Day","Daily Device Installs"
"2021-09-15",1
"2021-09-16",1

Then CSV Parser has a feature to use the header row with column-names. See the columns option.

Benefit:

  1. log the header
  2. map the column-names (for simple use in code)
  3. use it to make your code clean & expressive
  4. defend against changes of column-order inside the input CSV
var csvData=[];
let test = 0;

// options: use default delimiter comma and map header
let parser = parse({
  columns: header =>
    header.map( column => {
      console.log(column);  
      // could also map (e.g. similar to Snake_Case)
      return column.replace(/ /g,"_");
    })
}

function addToCounter(value) {
   if (!isNaN(value))
      console.log("WARN: not a number: ", value)
      return;
   test += value;
}

// read from file
fs.createReadStream(__dirname+'/test2.csv','utf16le').pipe(parser)
   .on('data', function(csvrow) {
      csvData.push(csvrow);
      addToCounter(csvrow.Daily_Device_Installs); // the column name as mapped with underscore
   })
   .on('end',function() {
      console.log(test)
   });

Note:

  • I extracted the counter-increment to a function.
  • Your csvData array now contains for each row an object (with column-names as keys) instead an array of columns.
about 4 years ago · Juan Pablo Isaza Denunciar

0

try

if (!isNaN(csvrow[2])) test += +csvrow[2];
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda