Search code examples
jqueryeachjquery-csv

Sum values in jQuery object by key


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?


Solution

  • 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);
        }
    });