【发布时间】:2019-06-21 14:30:34
【问题描述】:
当一个稀疏数组被排序[5, 2, 4, , 1].sort() -> [1, 2, 4, 5, empty]时,无论return语句如何,即使有回调,空值也总是最后。
我正在构建自己的排序方法作为挑战,我通过使用过滤器方法解决了这个问题,因为过滤器会跳过空值。然后迭代过滤数组并将原始数组的索引设置为过滤数组的值。然后我缩短了原始数组的长度,因为剩余的项目将是重复的,我终于可以在我的排序算法中提供它。完成后,我将它的长度设置回原来的,最后添加适当数量的空项目。这是一段 sn-p 代码,但这里是 a link of the entire code
const collectUndefined = [];
// remove empty items and collect undefined
const removeSparse = this.filter(el => {
if (el === undefined) {
collectUndefined.push(el);
}
return el !== undefined;
});
const tempLength = this.length;
// reset values but will contain duplicates at the end
for (let i = 0; i < removeSparse.length; i++) {
this[i] = removeSparse[i];
}
// shorten length which will remove extra duplicates
this.length = removeSparse.length;
// sort algorithm ...
// place undefineds back into the array at the end
this.push(...collectUndefined);
// restores original length and add empty elemnts at the end
this.length = tempLength;
return this
在处理稀疏数组时是否以这种类似的方式实现原生排序,或者没有。
【问题讨论】:
-
这与插槽为空无关。它们只是非数字的,因此它们和数字之间的所有(不)等式都返回
false。这可能是算法中的一个实现细节导致它们被移到最后,并且不太可能是规范的一部分。毕竟,JavaScript 中的内置排序是不稳定的。 -
注意:
[5, 2, 4, {}, 1].sort()->[1, 2, 4, 5, {}]
标签: javascript arrays sorting