The task at hand involves extracting "Dates" and "homeruns" from the provided .json file. The goal is to combine matching Dates together and sum up the homeruns corresponding to those dates. Currently, I have managed to display the combined Dates with their matching dates, but the Homeruns are not being added up; instead, they are just stacking next to each other. For instance, for Date: "1985", Hits: "3", Homeruns: "101".
chart.json
[{"Date": "1903", "Hits": "0", "Homeruns": "1"}, {"Date": "1903", "Hits": "1", "Homeruns": "2"}, ...
JS
function chartPage()
{
$.ajax(
{
url: 'chart.json',
data:
{},
dataType: 'json',
success: function(data)
{
var stringy = JSON.stringify(data);
var objects = $.parseJSON(stringy);
var categories = new Array();
var groupedObjects = new Array();
var i = 0;
_.each(objects, function(obj)
{
var existingObj;
if ($.inArray(obj.Date, categories) >= 0)
{
existingObj = _.find(objects, function(o)
{
return o.Date === obj.Date;
});
existingObj["Homeruns"] += obj["Homeruns"];
}
else
{
groupedObjects[i] = obj;
categories[i] = obj.Date;
i++;
}
});
groupedObjects = _.sortBy(groupedObjects, function(obj)
{
return obj["Homeruns"];
}).reverse();
// print results for testing
_.each(groupedObjects, function(obj)
{
var output = '';
_.each(obj, function(val, key)
{
output += key + ': ' + val + '<br>';
});
output += '<br>';
$('#results').append(output);
console.log(output);
});
}
});
}