Skip to content Skip to sidebar Skip to footer

Creating Series From Series In D3

I have data of this form (simplified, but assume 20 columns between Admin and Mining): Date,Series,Admin,Mining,CPI 1990,Ordinary Time Earnings,20,30,96 1991,Ordinary Time Earnings

Solution 1:

If you indeed use this code to "duplicate" your arrays:

OrdinaryTimeEarningsReal = OrdinaryTimeEarnings;TotalEarningsReal = TotalEarnings;

then you mentioned it right, when you said that they reference the same object. In JavaScript, arrays are mutable, and using the code above you just created 2 new variables with a reference to the existing array in the memory.

In order to deep clone your array of objects, use this method:

OrdinaryTimeEarningsReal = JSON.parse(JSON.stringify(OrdinaryTimeEarnings));TotalEarningsReal = JSON.parse(JSON.stringify(TotalEarnings));

This will create duplicates of the array and assign them to the new variables, so that when you'll edit them, the initial arrays will remain unaffected.

Now, regarding your code, it's a bit too complex. If I understood correctly what are you trying to achieve, you could simplify it as follows:

OrdinaryTimeEarningsReal
.forEach(function(z,i){for(var cin z){if(z.hasOwnProperty(c)&&c!=="Date"&&c!=="Series"&&c!=="CPI") 
            z[c]= z[c]/ z.CPI *100;       
    });
});

Good luck!

Solution 2:

If I understand correctly :

data.forEach(function(d) { 
  for (var key in d) {
    if (key !== 'Date' && key !== 'Series' && key !== 'CPI') {
      d['new' + key] = (d[key] / d.CPI) * 100;
    }
  }
})
console.log(data)

I have added new onto the new attributes so the new admin value is newAdmin

Implemented fiddle : https://jsfiddle.net/thatOneGuy/9ywLytjf/

Post a Comment for "Creating Series From Series In D3"