Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Parsing function only returns undefined instead of array

I can’t figure out why my function only returns undefined when it should be returning the array:

function parseData (dataFile){
d3.csv(dataFile).then(function(datapoints) {
    var barLabels = []
    var barData = []
    for (i=0; i < datapoints.length; i++){
        barLabels.push(Object.values(datapoints[i])[0]);
        barData.push(Object.values(datapoints[i])[1]);
    }
    
    //console.log(barLabels);
    return barLabels;

});
}

console.log(parseData('carbon-footprint-of-apparel-brands-2019.csv'));

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You are returning your array from the callback, instead of the parseData function. When your parseData function ends it returns undefined as you have not told it to return anything. Try this:

function parseData (dataFile){
  var barLabels = []
    d3.csv(dataFile).then(function(datapoints) {
        var barData = []
        for (i=0; i < datapoints.length; i++){
            barLabels.push(Object.values(datapoints[i])[0]);
            barData.push(Object.values(datapoints[i])[1]);
        }
    });

  return barLabels;
}

console.log(parseData('carbon-footprint-of-apparel-brands-2019.csv'));

By pulling the barLabels array outside of the d3.csv call and only pushing to it, you are free to return the array at the end. I also do not know what you are doing with the barData array, but if you are not using it you should remove it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading