d3.ascending()、d3.descending() 的替代方法,用于将未定义的值排序到底部
Alternative to d3.ascending(), d3.descending() for sorting undefined values to bottom
我有嵌套数组,其中的条目已分配给变量 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
值放在父数组的末尾,将定义的值放在顶部。
这很容易,因为您可以控制比较功能。
这就是 D3 实现升序的方式:
function ascending(a, b) {
return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
}
所以你需要做的就是用正确的顺序重新实现它 属性:
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
对于未定义和 null 均成立。
我有嵌套数组,其中的条目已分配给变量 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
值放在父数组的末尾,将定义的值放在顶部。
这很容易,因为您可以控制比较功能。
这就是 D3 实现升序的方式:
function ascending(a, b) {
return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
}
所以你需要做的就是用正确的顺序重新实现它 属性:
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
对于未定义和 null 均成立。