【问题标题】:D3.JS sort datapoints high to low?D3.JS 将数据点从高到低排序?
【发布时间】:2017-05-30 17:25:11
【问题描述】:

我在我的项目中使用 D3.JS,但不确定如何对传入的数据进行排序。我的 API 有以下内容:

[
  {
    "target": "target_one",
    "datapoints": [
      [
        8.0,
        1493510400.0
      ],
      [
        8.0,
        1493596800.0
      ]
    ]
  },
  {
    "target": "target_two",
    "datapoints": [
      [
        1.0,
        1493510400.0
      ],
      [
        1.0,
        1493596800.0
      ],
      [
        10.0,
        1493683200.0
      ]
    ]
  },
]

有没有一种方法可以使用 d3 将这些数据从高到低排序?任何建议都会很棒,谢谢!

【问题讨论】:

标签: javascript d3.js nvd3.js


【解决方案1】:

你可以用原始的 javascript 来做到这一点,使用这个原型函数

Array.prototype.orderByDescending = function (func) {
    this.sort((a, b) => {
        var a = func(a);
        var b = func(b);
        if (typeof a === 'string' || a instanceof String) {
            return b.localeCompare(a);
        }
        return b - a;
    });
    return this;
}

然后像这样调用它

elements.forEach(element=>{ element.datapoints.orderByDescending(p => p[0]) })

或者如果你不想污染原型,你可以使用普通函数

function orderByDescending (array,func) {
    array.sort((a, b) => {
        var a = func(a);
        var b = func(b);
        if (typeof a === 'string' || a instanceof String) {
            return b.localeCompare(a);
        }
        return b - a;
    });
    return array;
}

然后像这样调用它

elements.forEach(element=>{ orderByDescending(element.datapoints, p =>p [0])})

片段

Array.prototype.orderByDescending = function (func) {
    this.sort((a, b) => {
        var a = func(a);
        var b = func(b);
        if (typeof a === 'string' || a instanceof String) {
            return b.localeCompare(a);
        }
        return b - a;
    });
    return this;
}

var elements = [
  {
    "target": "target_one",
    "datapoints": [
      [
        8.0,
        1493510400.0
      ],
      [
        8.0,
        1493596800.0
      ]
    ]
  },
  {
    "target": "target_two",
    "datapoints": [
      [
        1.0,
        1493510400.0
      ],
      [
        1.0,
        1493596800.0
      ],
      [
        10.0,
        1493683200.0
      ]
    ]
  },
]

// order by  [0] point
elements.forEach(element=>{
    element.datapoints.orderByDescending(p=>p[0])
})

console.log('ordered descending by first element')
console.log(JSON.stringify(elements));

// order by  [1] point
elements.forEach(element=>{
    element.datapoints.orderByDescending(p=>p[1])
})

console.log('ordered descending by second element')
console.log(JSON.stringify(elements));

【讨论】:

  • 我应该在传递给 d3 之前进行排序吗?
  • 据我了解的问题,是的,应该先排序
  • 我建议不要污染 Array 原型。覆盖可能在未来浏览器版本中更新的系统对象通常是一个坏主意。您可以将其声明为普通函数。参考esdiscuss.org/topic/array-prototype-contains-solutions
  • 我同意你的观点,尽管这种方式在代码中更简洁。无论如何,我也在答案中添加了该选项
猜你喜欢
  • 2021-08-07
  • 2013-12-13
  • 2020-08-10
  • 2015-04-13
  • 2020-01-12
  • 2012-04-05
  • 1970-01-01
  • 1970-01-01
  • 2020-11-12
相关资源
最近更新 更多