sak0213
sak0213

Reputation: 31

Uncaught TypeError: [Array].filter is not a function

I'm trying to pass data from a flask api to chart.js. We're using D3 to make the api call:

var queryUrl = "http://127.0.0.1:5000/api/1/GenderOverTime";
var searchResults = [];

d3.json(queryUrl).then(function (chart_data) {
  searchResults = chart_data;});
  setTimeout(function(){init()},50)

Here is the section we're running into an error:

function init(){
  console.log("searchResults: ", searchResults);
  let selector = d3.select("#selDataset");
  let options = []
  filtered_data_for_chart = searchResults.filter(result=>{
      if (!options.includes(result.Sport)){
          options.push(result.Sport)
          selector
          .append("option")
          .text(result.Sport)
          .property("value", result.Sport);
      }
      
      return result.Sport==="Gymnastics"
  });

Upon running init(), we get "ChartJSfile.js:14 Uncaught TypeError: searchResults.filter is not a function".

Prior to using an api, we had another js script with the exact same data saved as an array object, and the chart & filter were working fine.

We added the setTimeout to allow some time to get the data, as the init() was running before data was loaded into the array.

sample of the data:

[{
    "_id": {
      "$oid": "61589a22cd5cc36ad5fc8898"
    },
    "Sport": "Aeronautics",
    "Year": 1936,
    "Sex": "M",
    "Name": 1,
    "Bronze": 0,
    "Silver": 0,
    "Gold": 1,
    "No Win": 0,
    "Attempts": 1,
    "Wins": 1
  },... ]

Upvotes: 2

Views: 4224

Answers (2)

Nicolas R
Nicolas R

Reputation: 293

Your code seems to work properly as you can see here

You might want to refactor it to be sure to have access to the data in search results when you need it:

var queryUrl = "http://127.0.0.1:5000/api/1/GenderOverTime";
var searchResults = [];

d3.json(queryUrl).then(function (chart_data) {
  searchResults = chart_data;
  init(searchResults);
});


function init(results) {
  console.log("searchResults: ", results);
  let selector = d3.select("#selDataset");
  let options = [];
  filtered_data_for_chart = results.filter((result) => {
    if (!options.includes(result.Sport)) {
      options.push(result.Sport);
      selector
        .append("option")
        .text(result.Sport)
        .property("value", result.Sport);
    }

    return result.Sport === "Gymnastics";
  });
}

Upvotes: 0

ABDULLOKH MUKHAMMADJONOV
ABDULLOKH MUKHAMMADJONOV

Reputation: 5234

You can use Array.from() to create a new, shallow-copied Array instance from an array-like or iterable object. So this should solve your issue:

const searchResultsList = Array.from(searchResults)
filtered_data_for_chart = searchResultsList.filter(result=>{...})

Upvotes: 1

Related Questions