3

I have a csv file converted to a jQuery object using jQuery CSV (https://github.com/evanplaice/jquery-csv/).

Here is the code for that:

    $.ajax({
        type: "GET",
        url: "/path/myfile.csv",
        dataType: "text",
        success: function(data) {
        // once loaded, parse the file and split out into data objects
        // we are using jQuery CSV to do this (https://github.com/evanplaice/jquery-csv/)

        var data = $.csv.toObjects(data);
    });

I need to sum up values by key in the object. Specifically, I need to add up the bushels_per_day values by company.

The object format is like so:

    var data = [
        "0":{
            beans: "",
            bushels_per_day: "145",
            latitude: "34.6059253",
            longitude: "-86.9833417",
            meal: "",
            oil: "",
            plant_city: "Decatur",
            plant_company: "AGP",
            plant_state: "AL",
            processor_downtime: "",
        },
        // ... more objects
    ]

This isn't working:

    $.each(data, function(index, value) { 
        var capacity = value.bushels_per_day;
        var company = value.plant_company.replace(/\W+/g, '_').toLowerCase();
        var sum = 0;
        if (company == 'agp') {
            sum += capacity;
            console.log(sum);
        }
    });

It just returns the value for each with a leading zero by company:

0145

0120

060

etc.

How can I do this?

Evan Plaice
  • 13,944
  • 6
  • 76
  • 94
joshuaiz
  • 415
  • 4
  • 13

2 Answers2

3

You need to use parseInt() to convert the strings to numbers. Otherwise,+` does string concatenation instead of addition.

Also, you need to initialize sum outside the loop. Otherwise, your sum gets cleared every time, and you're not calculating a total.

var sum = 0;
$.each(data, function(index, value) { 
    var capacity = parseInt(value.bushels_per_day, 10);
    var company = value.plant_company.replace(/\W+/g, '_').toLowerCase();
    if (company == 'agp') {
        sum += capacity;
        console.log(sum);
    }
});
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Barmar - yours is the closest - unfortunately I can't upvote you yet. This is returning the sum on each iteration. For example, it returns 145, 195, 255, ... 740 (which I know is the total). How can I grab just that final total? – joshuaiz Jan 29 '15 at 04:43
  • So obvious - just console.log(sum) outside of the loop. Thanks for the help! – joshuaiz Jan 29 '15 at 05:02
0

You are using a local variable sum inside $.each, which value is reassigned at every iteration, and your variable bushels_per_day is stringtyped, so JS just concatenate it's value with sum value

Try this. It worked for me

Fernando Carvalhosa
  • 1,098
  • 1
  • 15
  • 23