0

I have a dc.js program which runs fine when I give separate names to dc groups

var group1 = dateDimension.group().reduceSum(function(d) { return d.dd; });
var group2 = dateDimension.group().reduceSum(function(d) { return d.count; });

but when I do

    var groups = {};
    var columns   = ["dd","count"];

    for (var i = 0; i < columns.length; ++i) {
        var col = columns[i]
        groups[col] = dateDimension.group().reduceSum(function(d) { return d[col]; });
    }

it only remembers the last column and replaces other charts with last chart.

How should I solve this issue

Gaurav
  • 2,003
  • 1
  • 25
  • 50
  • 1
    also [don't enumerate arrays with for-in-loops, but iterate them](http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea) – Bergi Oct 25 '13 at 13:26

1 Answers1

1

The problem here is one that comes up all the time in JavaScript. Your variable "col" is scoped to the function where that for loop lives, and so it's shared by the two anonymous functions passed into the "reduceSum()" function.

The solution is to interpose another function to provide a distinct copy of the column name. (Also, you should not use for ... in to iterate through arrays.)

for (var i = 0; i < columns.length; ++i) {
  (function( columnName ) {
    group[ columnName ] = dateDimension.group().reduceSum(function(d) { return d[columnName]; });
  })( columns[i] );
}
Pointy
  • 405,095
  • 59
  • 585
  • 614
  • With all respect, is it really necessary to answer this for the 1000th time? A closevote would be more helpful. – georg Oct 25 '13 at 13:33
  • sorry for repetition closed it – Gaurav Oct 25 '13 at 13:40
  • 1
    @thg435 well the thing about this issue is that once you "get it", all the myriad manifestations look alike. However, *before* the light goes on, they don't, so other questions about the same topic may not clear up the confusion because the OP may not be able to see the similarity. I wish it were otherwise. – Pointy Oct 25 '13 at 13:55