Remove NaN values from data in D3.js

Here’s my code:

d3.csv('stockdataToPlot.csv', function(d){
  return {date : d3.timeParse("%Y-%m-%d")(d.Date), aapl : d.AAPL,
          aapl_sma: d.SMA_AAPL, tsla : d.TSLA, tsla_sma: d.SMA_TSLA}
}).then(plot_data);

I would like to remove the NaN values from d.SMA_AAPL and d.SMA_TSLA I would appreciate if someone helped me incorporate this example properly:

d3.csv('stockdataToPlot.csv', function(d){
  var data = d.filter(function(e){
        if(isNaN(e.value)){
            return false;
        }
        e.value = parseInt(e.value, 10);
        return true;
    });
  return {date : d3.timeParse("%Y-%m-%d")(d.Date), aapl : d.AAPL,
          aapl_sma: data.SMA_AAPL, tsla : d.TSLA, tsla_sma: data.SMA_TSLA}
}).then(plot_data);

The current error is TypeError: d.filter is not a function. Which is confusing because .filter takes a data array as a parameter, which should be d as referenced in the first line.

This is a nice compact line of code from the documentation: const result = words.filter(word => word.length > 6); How is this adapted? var data = d.filter(?? => ??.isNan(??));?

I’m sure I’m overthinking this, but I’m new to javascript and I don’t fully understand how this works. In python pandas I’d just do data.dropna() 🙁

Answer

Fixed:

d3.csv('stockdataToPlot.csv', function(d){
  function removeNaN(e,c){
    if(e>0){return e}else{return c}
  }
  return {date : d3.timeParse("%Y-%m-%d")(d.Date), aapl : d.AAPL,
          aapl_sma: removeNaN(+d.SMA_AAPL,d.AAPL), tsla : d.TSLA, tsla_sma: removeNaN(+d.SMA_TSLA,d.TSLA)}
}).then(plot_data);

In my case the NaN was registering as “” which defaults to 0 when passed through with a +. Luckily I didn’t have any values in my data less than or equal to 0. Instead of removing I replaced them with the same values as the close since it’s just a moving average. It’s not ideal but it’s okay for now.