If you can add the key "date" as another value of the object you can sort and group it, this will be quicker and more optimized when you have more values in the array.
[UPDATE]: fixed a little bug.
var arr = [{"date":"2013-03-02T00:00",val: 300}
, {"date":"2013-03-01T00:00",val: 200}
,{"date":"2013-03-02T00:00",val: 50}];
function groupArray(arr){
if(arr.length===0){return [];}
var pref,i;
// sort by date
arr.sort(function(a,b){
return (a.date>b.date)?1:(a.date<b.date)?-1:0;
});
// loop through the array grouping objects by date
pref=arr[0].date;
for(i=1;i<arr.length;i++){
if(arr[i].date===pref){
//set the total
arr[i-1].val=arr[i-1].val+arr[i].val;
//remove the element
arr.splice(i,1);
// set i one back
i--;
}
pref=arr[i].date;
}
return arr;
}
console.log(groupArray(arr));
A more complicated example is when you dynamically want to provide the key to sort on, in the example above the key is "hard coded" to be date but you maybe need to group on another key value, the following is a piece of code I had laying around that I've simplified to group by one key (original used an array of keys). You can pass a onMerge variable that should be a function that handles how to merge 2 items. This function is not generic and is specific to adding the val properties of the to be merged objects.
var arr = [{"date":"2013-03-02T00:00",val: 300}
, {"date":"2013-03-01T00:00",val: 200}
, {"date":"2013-03-01T00:00",val: 200}
, {"date":"2013-03-01T00:00",val: 200}
, {"date":"2013-03-01T00:00",val: 200}
,{"date":"2013-03-02T00:00",val: 50}];
/**
* @param arr is the array to be merged
* @param key is the key to use for merge
* (like date) will merge on items with same
* date value
* @param onMerge function to call when 2 items
* are merged with the 2 items as parameters
**/
function groupArray(arr,key,onMerge){
if(arr.length===0){return [];}
var pref,i;
// sort by key
arr.sort(function(a,b){
return (a[key]>b[key])?1:(a[key]<b[key])?-1:0;
});
// loop through the array grouping objects by key
pref=arr[0][key];
for(i=1;i<arr.length;i++){
if(arr[i][key]===pref){
//merge 2 items, call the onMerge callback
arr[i-1]=onMerge(arr[i-1],arr[i]);
//remove the element
arr.splice(i,1);
// set i one back
i--;
}
pref=arr[i][key];
}
return arr;
}
// functon that will be called when 2 items are merged
// stay will stay and gone will be gone
// this function is specific to your data type
function onMergeCallback(stay,gone){
stay.val=stay.val+gone.val;
return stay;
}
console.log(groupArray(arr,"date",onMergeCallback));