jQuery: Sum of all data appended with specific date

jquery, json, sum

Solution

I assume that what you have is a string like below,

"/ 07-09-2012 72.60 / 11-09-2012 194.98 / 03-09-2012 94.82 / 04-09-2012 187.56 / 31-10-2012 72 / 18-09-2012 204.75 / 26-09-2012 243.73 / 14-09-2012 86.40 / 20-09-2012 91.63 / 28-09-2012 96.56 / 01-09-2012 94.62 / 17-09-2012 94.86 / 17-09-2012 83.25 / 12-09-2012 94.85 / 18-09-2012 94.86 / 18-09-2012 68.74 / 21-09-2012 94.86 / 21-09-2012 94.86 / 24-09-2012 144.23 / 28-09-2012 92.77 / 30-09-2012 92.77 / 28-09-2012 92.77 / 13-09-2012 151.12 / 03-09-2012 125.80 / 05-09-2012 92.61 / 05-09-2012 95.54 / 12-09-2012 94.59 / 12-09-2012 94.59 / 13-09-2012 125.83 / 18-09-2012 109.38"

If that is the case then you need to parse the string to calculate the sum by month.

DEMO: http://jsfiddle.net/pBNNt/

Full Code:

var resultArr = result.split('/');
var results = {}; //sum by month
for (var i = 0; i < resultArr.length; i++) {    
    if ( resultArr[i].length >= 11) { //it has date
        var resultTkn = resultArr[i].split(' ');

        if (resultTkn[1].length == 10) { //it is a date
            var date = resultTkn[1].split('-');
            var sum = 0;
            if (results.hasOwnProperty(date[1])) {
                sum = results[date[1]];
            }

            sum += parseFloat(resultTkn[2]);
            results[date[1]] = sum;
        }
    }
}

Now you can access the sum by month using the results objects. `results["09"]` returned `3305.93`

Problem

I retrieve some data off an API and I append it as such: ``` if (jsontext == '[]') { return false } else { var newTr = ''; for (var i = 0; i < json.length; i++) { newTr += (' / ' + json[i].date + ' ' + json[i].price); } console.log(newTr); } ``` which gives me a huge list of results as such: / 07-09-2012 72.60 / 11-09-2012 194.98 / 03-09-2012 94.82 / 04-09-2012 187.56 / 31-10-2012 72 / 18-09-2012 204.75 / 26-09-2012 243.73 / 14-09-2012 86.40 / 20-09-2012 91.63 / 28-09-2012 96.56 / 01-09-2012 94.62 / 17-09-2012 94.86 / 17-09-2012 83.25 / 12-09-2012 94.85 / 18-09-2012 94.86 / 18-09-2012 68.74 / 21-09-2012 94.86 / 21-09-2012 94.86 / 24-09-2012 144.23 / 28-09-2012 92.77 / 30-09-2012 92.77 / 28-09-2012 92.77 / 13-09-2012 151.12 / 03-09-2012 125.80 / 05-09-2012 92.61 / 05-09-2012 95.54 / 12-09-2012 94.59 / 12-09-2012 94.59 / 13-09-2012 125.83 / 18-09-2012 109.38 and keep's going. How can I take the sum of the pricing for the month 09? The date format is dd-mm-yyyy.

Original source