正如标题所示,我只对 ES5 之前的普通 JS 感兴趣。待排序的数组 (a) 仅包含非负整数 (0,1,2,3...)。而且顺序并不重要。
我不确定 filter、reduce 或 for 循环哪个更快:
1) 过滤器
uniqueArray = a.filter(function(item, pos) {
return a.indexOf(item) == pos;
})
2)减少
var unique = a.reduce(function(reduceArray,currentValue){
if (reduceArray.indexOf(currentValue) < 0 ) reduceArray.push(currentValue);
return reduceArray;
},[]);
3) 对于
var hash = [],
unique = [];
for (var i= 0, len = a.length; i<len; i++) {
if (!hash[a[i]]) {
unique.push(a[i]);
}
hash[a[i]] = true;
}
我认为for循环的性能最好。我的推理:
- for 循环的运行时间复杂度为 O(n)
- JS 中的函数调用非常昂贵。 filter和reduce正在调用一个函数。 for 循环没有
我的推理可以吗?有没有更有效的方法来删除重复项?
最佳答案
我相信就是这样;
var myArray = [100, 200, 100, 200, 100, 100, 200, 200, 200, 200],
unified = Object.keys(myArray.reduce(function(p,c) {p[c] = true; return p;},{}));
console.log(unified);
关于javascript - 使用 vanilla JS 删除 ES5 及以下版本数组中的重复数字的最快方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37880027/