0

I need to write a function which will filter out relevant data from a csv file and return an array containing the data. The csv file contains time as one of the columns and I want to filter out the rows within specified start and end time as provided in function arguments. I have written the follwing function filter_data(please also note that this uses d3.js):

   <code>
    function filter_data(start_time, end_time) {
         var formatDate = d3.time.format("%H:%M"),
         parseDate = formatDate.parse;
         var data1 = [];
         d3.csv("data.txt", function(error, data) {
             data.forEach(function(d) {
                 if(parseDate(d.time) >= parseDate(start_time) && parseDate(d.time) < parseDate(end_time))
                     data1.push(d);    
             });
          return data1;
         });
    }
</code>

The idea behind this was to build reusable code for getting data. But the above function always returns undefined. I have deliberately placed the return value inside the callback function as I know this will be an asynchronous call (I also trie placing return statement at the end, but it returns empty array!).

abksrv
  • 1,347
  • 1
  • 15
  • 34

1 Answers1

1

You can't use a return in this instance. You need to pass a callback function as one of the arguments for filter_data and use that to return the data.

function filter_data(start_time, end_time, callback) {
  var formatDate = d3.time.format("%H:%M"),
  parseDate = formatDate.parse;
  var data1 = [];
  d3.csv("data.txt", function(error, data) {
    data.forEach(function(d) {
      if(parseDate(d.time) >= parseDate(start_time) && parseDate(d.time) < parseDate(end_time)) {
        data1.push(d);
      }
    });
    callback(data1);
  });
}

filter_data(start_time, end_time, function (data) {
  console.log(data);
});
Andy
  • 61,948
  • 13
  • 68
  • 95
  • That error is caused by something else. Check that the data is being returned correctly from `d3.csv`. – Andy Sep 15 '14 at 10:11