How to convert a filtered array with strings to an array with integers

Viewed 26

I filtered an array and now I'm using .map() to convert each element in the array to an integer. This returns an array that contains "NaN" only. My goal here is to return the array converted into integers.

fetchData = d3.csv("https://gist.githubusercontent.com/dakoop/9e67814b6073ebbf6e7f55e31b5781ce/raw/5dad34b939d0d0789570064a75b145cc255f2811/newspaper-circulation.csv");
{
  const a = fetchData;
  var b = a.filter(d => d.Year != "1940" && d.Year != "2010");
  return b.map(x => parseInt(x))
}
1 Answers

From the code presented it's not pretty sure your intention, but there are some errors need to check. d3.csv() does not return an array with the data, it returns a request. This request is asynchronous, it means "shoot and forget", so the data is not available immediately after the call. That's why you need a callback function to be called when the data is already available, in that function you can handle the data :

d3.csv("https://gist.githubusercontent.com/dakoop/9e67814b6073ebbf6e7f55e31b5781ce/raw/5dad34b939d0d0789570064a75b145cc255f2811/newspaper-circulation.csv", function(data) {
    console.log(data);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

There are other functions available to handle the data as an array. Take a look at How to read in CSV with d3 v4?

Related