简体   繁体   中英

Removing empty cells (rows) from csv file in javascript

在此处输入图片说明 I am calling a csv file to make a chart in chart.js. It splits the data into two arrays but the data (csv file) contains two empty rows at the bottom creating two empty data points. I've tried this line of code to try to eliminate the empty data points but it seems to only remove one (there are two empty rows at the bottom). Is there something I am doing wrong or is there a better way to do this?

    if(rows[rows.length-1] ===""){
        rows.pop()
    }

The full code here:

      async function getData() {
        // const response = await fetch('testdata.csv');
        var response = await fetch('https://www.bankofcanada.ca/valet/observations/FXCADUSD/csv?recent_weeks=1');
        var data = await response.text();
        data = data.replace(/"/g,"");

        var years = [];
        var temps = [];
        var rows = data.split('\n').slice(9);

        if(rows[rows.length-1] ===""){
            rows.pop()
        }

        rows.forEach(row => {
          var cols = row.split(",");
          years.push(cols[0]);
          temps.push(0 + parseFloat(cols[1]));
        });
        console.log (years, temps );
        return { years, temps };

If you know the last two rows are empty just slice them off using slice ( Array.prototype.slice )

 rows = rows.slice(0, rows.length - 2);

 let a = [1,2,3,4,5]; a = a.slice(0, a.length-2); console.log(a);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM