我有一组数字,我需要确保它们是唯一的。我在互联网上找到了下面的代码片段,它工作得很好,直到数组中有一个零。我在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数组中删除重复值

类似的问题:

获取数组中的所有非唯一值(即:重复/多次出现)


当前回答

我们可以使用ES6集合来实现这一点:

var duplicatesArray=[1,2,3,4,5,1,1,2,4,4];var uniqueArray=[…new Set(duplicatesArray)];console.log(uniqueArray);//[1,2,3,4,5]

其他回答

重复数据消除通常需要给定类型的相等运算符。然而,使用eq函数会阻止我们以有效的方式使用Set来确定重复项,因为Set返回到==。如您所知,==不适用于引用类型。所以,如果被卡住了,我们会很好,对吧?

解决方法是简单地使用一个转换器函数,它允许我们将一个(引用)类型转换为我们可以使用Set实际查找的类型。例如,如果数据结构不包含任何函数,我们可以使用哈希函数或JSON.stringify数据结构。

通常我们只需要访问一个属性,然后我们就可以比较它而不是Object的引用。

以下是满足这些要求的两个组合子:

常量重复数据消除On=k=>xs=>{const s=new Set();返回xs.filter(o=>s有(o[k])? 无效的:(s.add(o[k]),o[k]]);};常量重复数据消除By=f=>xs=>{const s=new Set();返回xs.filter(x=>{常量r=f(x);返回s.has(r)? 无效的:(s.add(r),x);});};const xs=[{foo:“a”},{foo:“b”};控制台日志(重复数据删除打开(“foo”)(xs));//〔{foo:“a”},{foo:“b”}、{foo:“a”}和{foo:“c”}〕控制台日志(重复数据删除方式(o=>o.foo.toLowerCase())(xs));//〔{foo:“a”}、{foo:“b”},{foo:“c”}〕

使用这些组合器,我们可以非常灵活地处理各种重复数据消除问题。这不是禁食的方法,而是最具表现力和通用性的方法。

下面是另一种使用比较器的方法(我更关心干净的代码而不是性能):

const list = [
    {name: "Meier"},
    {name: "Hans"},
    {name: "Meier"},
]
const compare = (a, b) => a.name.localeCompare(b.name);
const uniqueNames = list.makeUnique(compare);
uniqueNames.pushIfAbsent({name: "Hans"}, compare);

原型声明:

declare global {
    interface Array<T>  {
        pushIfAbsent(item: T, compare:(a:T, b:T)=>number): number;
    }
    interface Array<T>  {
        makeUnique(compare:(a:T, b:T)=>number): Array<T>;
    }
}
Array.prototype.pushIfAbsent = function <T>(this:T[], item:T, compare:(a:T, b:T)=>number) {
    if (!this.find(existing => compare(existing, item)===0)) {
        return this.push(item)
    } else {
        return this.length;
    }
}
Array.prototype.makeUnique = function <T>(this:T[], compare:(a:T, b:T)=>number) {
    return this.filter((existing, index, self) => self.findIndex(item => compare(existing, item) == 0) == index);
}

使用Set删除重复项。

具有重复项的阵列

const withDuplicates = [2, 2, 5, 5, 1, 1, 2, 2, 3, 3];

使用Set获取不重复的新数组

const withoutDuplicates = Array.from(new Set(withDuplicates));

较短版本

const withoutDuplicates = [...new Set(withDuplicates)];

结果:[2,5,1,3]

使用ES6新设置

变量数组=[3,7,5,3,2,5,2,7];var unique_array=[…新集合(数组)];console.log(unique_array);//输出=[3,7,5,2]

使用For循环

变量数组=[3,7,5,3,2,5,2,7];for(var i=0;i<array.length;i++){for(变量j=i+1;j<array.length;j++){如果(array[i]===array[j]){阵列.拼接(j,1);}}}console.log(数组);//输出=[3,7,5,2]

设ar=[1,2,3,4,5,6,1,2,4,2,1];let unique=ar.filter((值,索引)=>{return ar.indexOf(value)==索引;});console.log(唯一);