Colin
Colin

Reputation: 940

Javascript (D3) loop optimization

I'm trying to pre-process some data. While my approach works, it feels really dirty.

    // Calculate dataset mean
    var mean = Math.round(d3.mean(data, function(d) { return d.value; }));

        // Iterate through data reformatting dates and centering data around the mean
        data.forEach(function(d) {
                parseDate = d3.time.format("%Y-%m-%d").parse;
                d.date = parseDate(d.date);
                d.value = Math.round(+d.value - mean);
        });

   var data = data.map(function(obj) { return [obj.date.getTime(), obj.value]; });

I'm essentially looping through the dataset three times.

First, to calculate the mean (which is only used in the next loop).

Second, to reformat date strings and center the data around the mean.

Third, to cast the date string to a date object (epoch time).

There has got to me a more efficient way than iterating through the dataset three times.

How might I consolidate these loops?

Upvotes: 0

Views: 103

Answers (1)

Lars Kotthoff
Lars Kotthoff

Reputation: 109282

Well you need the mean in the second iteration, so there's no way to get around the first iteration. You can easily combine iterations 2 and 3 though:

var parseDate = d3.time.format("%Y-%m-%d").parse;
var data = data.map(function(d) {
  d.date = parseDate(d.date);
  d.value = Math.round(+d.value - mean);
  return [d.date.getTime(), d.value];
});

Unless data is very large (at least thousands of items), this won't make it noticeably more efficient.

Upvotes: 2

Related Questions