Cal*_*lor 5 javascript arrays sorting
对稀疏数组进行排序时[5, 2, 4, , 1].sort() -> [1, 2, 4, 5, empty],无论return语句如何,即使有回调,空值也始终是最后一个。
我正在构建自己的排序方法来应对挑战,由于过滤器跳过了空值,因此我使用过滤器方法解决了此问题。然后遍历过滤后的数组并将原始数组的索引设置为过滤后的数组的值。然后,我缩短了原始数组的长度,因为剩余的项将是重复项,最后可以将其输入我的排序算法中。完成此操作后,我将其长度设置回原始长度,并在末尾添加适当数量的空项目。这是一段代码,但这是整个代码的链接
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
Run Code Online (Sandbox Code Playgroud)
处理稀疏数组时是否以这种类似方式实现本机排序,否则,否。