0

So, I have been trying to wrap my head around d3.js and cannot for the life of me figure out a way to splice an array. In the code below, i am importing a csv file (which has >30000 rows) and then trying to subset it to the first 40 values by splicing the array. While the command works in the console tab (i.e. data.splice(0,40)), it doesn't work within the script. What am i doing wrong?

<script src="//d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/d3-array.v1.min.js"></script>
<script>
d3.csv("for_musp.csv", function(data2) {
  data = data2.map(function(d) { return +d["label"] ; });
});
var newData = data.splice(0,40);

};
</script>
aragorn87
  • 3
  • 1

1 Answers1

1

Try this (callback for d3.csv is asynchronous):

var newData;
d3.csv("for_musp.csv", function(data2) {
  data = data2.map(function(d) { return +d["label"] ; });
  newData = data.splice(0,40);
});
Ivan
  • 876
  • 1
  • 8
  • 22
  • thanks! this works! however, what is asynchronous? any resource i can go through? – aragorn87 Nov 03 '17 at 18:02
  • https://github.com/d3/d3-request/blob/master/README.md#csv it's documentation fo d3, for asynchronous javascript try here and then google: https://developers.google.com/web/fundamentals/primers/promises – Ivan Nov 03 '17 at 18:03
  • in two words, code in callback will run not in order that it's written, but when file reading done, so all operations about data from file should be executed inside callback. – Ivan Nov 03 '17 at 18:08
  • Thanks Ivan! makes sense. Hoewever, I now want to pop an element from the newData and add the next point from data to the newData array. This has to be iterated over a loop. What would be the best way to go about it. – aragorn87 Nov 03 '17 at 18:12
  • depends on from which side of array you want to get it, google for `Array.pop()`, `Array.push()`, `Array.shift()`, `Array.unshift()`, – Ivan Nov 03 '17 at 18:16