Sum values in jQuery object by key

烈酒焚心 提交于 2019-12-05 20:53:04

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!