【发布时间】: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