Sufi Iman Sufi Iman - 1 year ago 40
jQuery Question

Increment value of array object by using values of another array's objects

I'm trying to figure out how to get cumulative values from a data table that a user enters values in. I've stored all of the data into an array representing the raw data, and I am trying to increment an array which is a copy of the array representing the raw data in order to obtain the cumulative data for the graph. I am trying to do this by incrementing each value object of the array to the values of each index of the raw data array up to the current index. I'm doing this through a loop, but it doesn't seem to be working. My code for the function is here:

function generateChartData() {
var rawData = [];
var chartData = [];
jQuery('.data-row').each(function () {
var date = jQuery(this).find('.data-category').val();
var value = jQuery(this).find('.data-value').val();
var value2 = jQuery(this).find('.data-value2').val();
if (date != '') {
date: date,
value: value,
value2: value2

for (var i = 0; i < rawData.length; i++)
chartData[date][i] = rawData[date][i];
for(var j = i; j >= 0; j--)

return chartData;

Here is the jsfiddle

Answer Source

You're not properly accessing array and object elements. And you can just use a simple variable to hold the running total.

var valueSum = 0;
var value2Sum = 0;
for (var i = 0; i < rawData.length; i++) {
    rd = rawData[i];
    valueSum += rd.value;
    value2Sum += rd.value2;
        value: valueSum,
        value2: value2Sum