【问题标题】:Alternative to d3.ascending(), d3.descending() for sorting undefined values to bottomd3.ascending()、d3.descending() 的替代方案,用于将未定义的值排序到底部
【发布时间】:2015-03-12 18:23:34
【问题描述】:

我有一个嵌套数组,其中的条目分配给变量persons

[
    {
        "person": "test",
        "why": "why test",
        "third": "third entry"
    },
    {
        "person": "test",
        "why": "why test",
        "third": ""
    }
]

通常我会使用 d3.ascending/descending 按字母顺序对数组进行排序。

persons = persons.sort(function (a,b) { return d3.ascending(a[2], b[2]);});

但是,当数组包含undefined 值时,这不适用于排序。 From the d3.js documentation:

Unlike the built-in Math.min, this method ignores undefined values;

还有什么方法可以对值进行排序?我想将 undefined 值放在父数组的末尾,并将定义的值放在顶部。

【问题讨论】:

  • 您可以提供自己的比较函数。
  • 类似:type(a[2]) === 'undefined' < b[2] ?
  • 如果你只关心定义,即使a[2] === undefined < b[2] === undefined

标签: javascript arrays sorting d3.js


【解决方案1】:

这很容易,因为您可以控制比较功能。

这就是 D3 实现升序的方式:

function ascending(a, b) {
  return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
}

所以你需要做的就是用具有正确排序属性的 undefined 重新实现它:

persons = persons.sort(function (a, b) {
  return b[2] == null ? (a[2] == null ? 0 : -1) 
          : b[2] < a[2] ? -1 : b[2] > a[2] ? 1 : b[2] >= a[2] ? 0 : NaN;
});

显然,您可以将此函数提取为单独的通用比较器。

降序将是它的倒数。

请注意,在 JS 中,a == null 对 undefined 和 null 都是 true。

【讨论】:

    猜你喜欢
    • 2013-04-10
    • 1970-01-01
    • 1970-01-01
    • 2014-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-05
    • 1970-01-01
    相关资源
    最近更新 更多