danpker
danpker

Reputation: 613

Why is push() not working inside a loop?

I have some code:

  var cdata = [];

  d3.text("tests.info", function(text) {
    var data = d3.csv.parseRows(text);
    data.forEach(function(d) {
        cdata.push({key: d[0],values: []}
      );
    });
  });

It's reading in a CSV file and then looping though the lines before adding them into the array. I've used logs to see that the data is getting added correctly so this is fine.

The issue is that if I try and access the array afterwards, it is empty, as if the data was never added (although I know this isn't true).

I think it is something to do with scoping, but I thought that push() should work in this way regardless.

Upvotes: 1

Views: 2442

Answers (2)

user663031
user663031

Reputation:

You need to return cdata:

d3.text("tests.info", function(text) {
  var data = d3.csv.parseRows(text), cdata = [];
  data.forEach(function(d) {
    cdata.push({key: d[0],values: []};
  });
  return cdata;
});

Consider also just doing

d3.text("tests.info", function(text) {
  return d3.csv.parseRows(text).map(function(d) {
    return {key: d[0], values: []};
  });
});

Upvotes: 0

Mimu
Mimu

Reputation: 393

Try to console.log inside a timeout function, or put a button that display cdata's content and you'll see that it is not empty. As Pointy said, what happen is:

  • You declare cdata

  • You start loading test.info

  • You display cdata's content

  • test.info is loaded, you start looping and putting data in your array

Upvotes: 2

Related Questions