d3js:如何从数据中仅选择x个值

时间:2017-10-25 08:49:00

标签: javascript css d3.js

我有以下格式的数据:

var data = [
  {name: "A", rank: 0, c: 92}, 
  {name: "B", rank: 45, c: 99},
  {name: "C", rank: 89, c: 89},
  {name: "D", rank: 23, c: 99},
  {name: "E", rank: 56, c: 98}
];

我想找到这些数据的一个子集,比如说只有3个值。我不知道怎么做这个是d3js。我发现的解决方案主要基于以下数据的属性:

data = data.filter(function(d){return +d.rank < 10});

但这给了我所有数据点的等级&lt; 10但我想根据一些用户输入来限制数据的“大小”(数据点的数量)。

我该怎么做?

1 个答案:

答案 0 :(得分:3)

使用filter + slice

可能是这样的

&#13;
&#13;
var data = [
  {name: "A", rank: 0, c: 92},

  {name: "B", rank: 45, c: 99},

  {name: "C", rank: 89, c: 89},

  {name: "D", rank: 23, c: 99},

  {name: "E", rank: 56, c: 98}
];
var size = 3; //user input size that is needed
var result = data.filter(function(d) {return (+d.rank > 10)}).slice(0,size)
console.log(result)
&#13;
&#13;
&#13;