Only just introduced to _Underscore so this may be totally nonsense but I'm wondering if the library can indeed do what I want.
I have an object containing 5 items:
Name, v2007,v2008,v2009,v2010
I simply want to go through the entire object and get the SUM of each distinct value in Name (much similar to SQL's GroupBy and SUM).
I have the following:
var distincts = [];
$.each(tmp, function (key, value) {
$.each(value, function (fieldName, fieldValue) {
if (fieldName == 'Name') {
if ($.inArray(fieldValue, distincts) == -1) {
distincts.push(fieldValue);
}
}
});
});
$.each(distincts, function (a, b) {
var t = _.where(tmp, {Name: b});
var sum = _.reduce(t.v2007, function (memo, num) {
return memo + num;
}, 0)
console.log(sum);
});
Which is returning 0 all the time, in fact I'm not sure how to retrieve a SUM of fields v2011, v2013 other than hard-coding them in which is simply not practical!
Can someone help me a little here, is there a simple way of getting the _Underscore library to SUM all fields (that, say, start with 'v') based on a Group of the Name?
tmpobject (in JSON format)? Btw, you shouldn't mix Underscore's and jQuery'seachfunctions