Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

86
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

0

try

if (!isNaN(csvrow[2])) test += +csvrow[2];
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda