首页 > 解决方案 > 使用数组过滤器从 csv 过滤数据未按预期工作

问题描述

我的数据以csv格式如下。

Id,Title,Year,Runtime,Country,imdbRating,imdbVotes,Budget,Gross,WinsNoms,IsGoodRating 13,Alone in the Dark,2005,96,"Canada, Germany, USA",2.3,37613,20000000,8178569,9, 0 38,Boogeyman,2005,89,"美国,新西兰,德国",4.1,25931,20000000,67192859,0,0 52,Constantine,2005,121,"美国,德国",6.9,236091,75000000,221594911 ,11,1 62,疯狂黑人妇女日记,2005,116,USA,5.6,10462,5500000,50458356,26,0 83,Fever Pitch,2005,104,“美国,德国”,6.2,36198,40000000 ,50071069,9,1

我试图过滤出如下数据,但没有一个过滤工作。

d3.csv("movies.csv", function(error, data) {
  // change string (from CSV) into number format
  data.forEach(function(d) {
    d.imdbRating = +d.imdbRating;
    d["WinsNoms"] = +d["WinsNoms"];
    d["IsGoodRating"] = +d["IsGoodRating"]
  });

  var rating0 = data.filter(function(d){ return d["IsGoodRating"] = 0});
  rating0.forEach(function(d) { console.log(d); }); 
  //the above line does not give me anything on the console
  var rating1 = data.filter(function(d){ return d["IsGoodRating"] = 1});
  rating1.forEach(function(d) { console.log(d); }); 
  //the above line gives me an output of all the records with both IsGoodRating which are 0 and 1 but the output shows as 1 which is not what the data has.

任何帮助将不胜感激。我是 d3.js 的新手,所以我可能会犯一个基本错误。

标签: d3.jsarray-filter

解决方案


执行与以下相同的操作按预期工作,但数组过滤器没有。

  var rating0 = data.filter(function(d)
  {
    if (d["IsGoodRating"] == 0)
    {
      return d;
    }
  })
 // var rating0 = data.filter(function(d){ return d.IsGoodRating = 0}); This array filter is not working for some reason
  rating0.forEach(function(d) { console.log(d.IsGoodRating); });

  var rating1 = data.filter(function(d)
  {
    if (d["IsGoodRating"] == 1)
    {
      return d;
    }
  })
 // var rating1 = data.filter(function(d){ return d["IsGoodRating"] != 0});This array filter is not working for some reason
  rating1.forEach(function(d) { console.log(d.IsGoodRating); });

推荐阅读