首页 > 解决方案 > 在内部数组中查找域值

问题描述

我有一个这样的数据集:

const dataset = [
      { 'color': 'red', 'data': [{ x: 0, y: 600 }, { x: 2, y: 900 }, { x: 4, y: 650 }, { x: 6, y: 700 }, { x: 9, y: 600 }] },
      { 'color': 'blue', 'data': [{ x: 0, y: 400 }, { x: 2, y: 300 }, { x: 4, y: 450 }, { x: 6, y: 900 }, { x: 9, y: 400 }] },
      { 'color': 'yellow', 'data': [{ x: 0, y: 200 }, { x: 2, y: 100 }, { x: 4, y: 550 }, { x: 6, y: 600 }, { x: 9, y: 400 }] }
    ];

我想找到最大和最小 x 轴的域值。我尝试了这段代码,但它不起作用:

.domain([d3.min(arrangedata, (array) => array.x), d3.max(arrangedata, (array) => array.x)])

我也试过d3.extend,但我无法处理它。任何想法 ?

标签: javascriptd3.js

解决方案


对于使用d3.max/minor d3.extent,您必须合并内部数组,您可以使用Array.prototype.reduce. 然后,x在访问器中指定属性。

总之,就是这样:

const extent = d3.extent(dataset.reduce((a, c) => a.concat(c.data), []), d => d.x);

这是演示:

const dataset = [{
    'color': 'red',
    'data': [{
      x: 0,
      y: 600
    }, {
      x: 2,
      y: 900
    }, {
      x: 4,
      y: 650
    }, {
      x: 6,
      y: 700
    }, {
      x: 9,
      y: 600
    }]
  },
  {
    'color': 'blue',
    'data': [{
      x: 0,
      y: 400
    }, {
      x: 2,
      y: 300
    }, {
      x: 4,
      y: 450
    }, {
      x: 6,
      y: 900
    }, {
      x: 9,
      y: 400
    }]
  },
  {
    'color': 'yellow',
    'data': [{
      x: 0,
      y: 200
    }, {
      x: 2,
      y: 100
    }, {
      x: 4,
      y: 550
    }, {
      x: 6,
      y: 600
    }, {
      x: 9,
      y: 400
    }]
  }
];

const extent = d3.extent(dataset.reduce((a, c) => a.concat(c.data), []), d => d.x);

console.log(extent)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>


推荐阅读