Reputation: 11
I am trying to read in some csv data, select a specific column(SST), and create an array where each item is: { x: row#, y: SST_for_that_row }.
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var dat=[];
d3.csv("stratus2.txt", function(t) {
dat = t;
});
f=dat.map(function(d,i) {
return {x:i,y:d.SST}
</script>
My firefox console shows me that the "dat" variable is successfully loaded, but "f" is empty. However, if I directly type the following into the console, it loads just fine.
f=dat.map(function(d,i) {
return {x:i,y:d.SST}
Is there perhaps some sort of scoping issue? Thanks in advance, Ben
Upvotes: 0
Views: 241
Reputation: 1085
I think you're running into issues keeping your map and return out of your csv callback. What's going on is your csv
code hasn't finished (dat isn't set to t), but the callback doesn't block (d3.csv() is asynchronous), so your javascript keeps running, leaving you with an empty map.
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var dat=[];
d3.csv("stratus2.txt", function(t) {
dat = t;
f=dat.map(function(d,i) {
return {x:i,y:d.SST};
});
});
</script>
Try it this way instead, and check out Javascript synchronous vs asynchronous for more information.
The reason this works in your console is because by the time you're entering those lines of code in, your callback has already processed, so dat
does have an assigned value.
Upvotes: 2