我有一组数字,我需要确保它们是唯一的。我在互联网上找到了下面的代码片段,它工作得很好,直到数组中有一个零。我在Stack Overflow上找到了另一个脚本,看起来几乎与它完全一样,但它不会失败。
所以为了帮助我学习,有人能帮我确定原型脚本哪里出错吗?
Array.prototype.getUnique = function() {
var o = {}, a = [], i, e;
for (i = 0; e = this[i]; i++) {o[e] = 1};
for (e in o) {a.push (e)};
return a;
}
重复问题的更多答案:
从JS数组中删除重复值
类似的问题:
获取数组中的所有非唯一值(即:重复/多次出现)
在简单方法中查找唯一的数组值
function arrUnique(a){
var t = [];
for(var x = 0; x < a.length; x++){
if(t.indexOf(a[x]) == -1)t.push(a[x]);
}
return t;
}
arrUnique([1,4,2,7,1,5,9,2,4,7,2]) // [1, 4, 2, 7, 5, 9]
如前所述,[…new Set(value)]是最好的选项,如果您可以使用的话。
否则,这里有一个单行程序,它不会为每个索引迭代数组:
values.sort().filter((val, index, arr) => index === 0 ? true : val !== arr[index - 1]);
这只是将每个值与前面的值进行比较。结果将被排序。
例子:设值=[1,2,3,3,4,5,5,4,4,3,1,1,3,3];let unique=values.sort().filter((val,index,arr)=>索引==0?真:val!==arr[索引-1]);console.log(唯一);
您也可以使用sugar.js:
[1,2,2,3,1].unique() // => [1,2,3]
[{id:5, name:"Jay"}, {id:6, name:"Jay"}, {id: 5, name:"Jay"}].unique('id')
// => [{id:5, name:"Jay"}, {id:6, name:"Jay"}]