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

类似的问题:

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


当前回答

桩的另一个解决方案。

我最近需要使一个排序列表唯一,我使用过滤器来跟踪对象中的前一项,如下所示:

uniqueArray = sortedArray.filter(function(e) { 
    if(e==this.last) 
      return false; 
    this.last=e; return true;  
  },{last:null});

其他回答

这个原型getUnique并不完全正确,因为如果我有一个类似于[“1”,1,2,3,4,1,“foo”]的数组,它将返回[“1“,“2”,“3”,“4”],“1”是字符串,1是整数;它们是不同的。

以下是正确的解决方案:

Array.prototype.unique = function(a){
    return function(){ return this.filter(a) }
}(function(a,b,c){ return c.indexOf(a,b+1) < 0 });

使用:

var foo;
foo = ["1",1,2,3,4,1,"foo"];
foo.unique();

以上将产生[“1”,2,3,4,1,“foo”]。

魔术

a.filter(e=>!(t[e]=e in t)) 

O(n)性能-我们假设您的阵列位于a中,且t={}。此处解释(+Jeppe impr.)

让unique=(a,t={})=>a.filter(e=>!(t〔e〕=e in t));//使用全局t的“单机”版本://a1.过滤器((t={},e=>!(t[e]=e in t));//测试数据设a1=[5,6,0,4,9,2,3,5,0,3,4,1,5,4,9];设a2=[[2,17],[2,17]、[2,17]、[1,12]、[5,9]、[1,12]、[6,2],[1,12]];设a3=[“迈克”、“亚当”、“马特”、“南希”、“亚当斯”、“珍妮”、“南茜”、“卡尔”];//结果console.log(JSON.stringify(唯一(a1)))console.log(JSON.stringify(唯一(a2)))console.log(JSON.stringify(唯一(a3)))

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

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);
}

使用JavaScript 1.6/ECMAScript 5,您可以通过以下方式使用Array的本机筛选器方法来获得具有唯一值的数组:

仅函数唯一(值、索引、自身){return self.indexOf(value)==索引;}//用法示例:var a=['a',1,'a',2,'1'];var unique=a.filter(仅唯一);console.log(唯一);//[阿',1,2,'1']

本机方法筛选器将循环遍历数组,并只保留那些传递给定回调函数的条目。

如果给定值是第一个出现,则仅唯一检查。如果没有,它必须是副本,并且不会被复制。

这个解决方案不需要任何额外的库,如jQuery或prototype.js。

它也适用于具有混合值类型的数组。

对于不支持本机方法filter和indexOf的旧浏览器(<ie9),您可以在MDN文档中找到filter和indexOf的解决方法。

如果要保留值的最后一次出现,只需将indexOf替换为lastIndexOf。

使用ES6,这可以缩短为:

//用法示例:var myArray=['a',1,'a',2,'1'];var unique=myArray.filter((v,i,a)=>a.indexOf(v)==i);console.log(唯一);//唯一的是['a',1,2,'1']

感谢卡米洛·马丁的评论提示。

ES6有一个本地对象Set来存储唯一值。要获得具有唯一值的数组,现在可以执行以下操作:

var myArray=['a',1,'a',2,'1'];let unique=[…new Set(myArray)];console.log(唯一);//唯一的是['a',1,2,'1']

Set的构造函数接受一个可迭代的对象,如Array,而扩展运算符。。。将集合转换回数组。感谢Lukas Liese的评论提示。

对于一个元组数组,我将把它们放到一个Map中,让它完成工作。使用此方法时,您必须注意要使用的密钥:

const arrayOfArraysWithDuplicates = [
    [1, 'AB'],
    [2, 'CD'],
    [3, 'EF'],
    [1, 'AB'],
    [2, 'CD'],
    [3, 'EF'],
    [3, 'GH'],
]

const uniqueByFirstValue = new Map();
const uniqueBySecondValue = new Map();

arrayOfArraysWithDuplicates.forEach((item) => {
    uniqueByFirstValue.set(item[0], item[1]);
    uniqueBySecondValue.set(item[1], item[0]);
});

let uniqueList = Array.from( uniqueByFirstValue, ( [ value, name ] ) => ( [value, name] ) );

console.log('Unique by first value:');
console.log(uniqueList);

uniqueList = Array.from( uniqueBySecondValue, ( [ value, name ] ) => ( [value, name] ) );

console.log('Unique by second value:');
console.log(uniqueList);

输出:

Unique by first value:
[ [ 1, 'AB' ], [ 2, 'CD' ], [ 3, 'GH' ] ]

Unique by second value:
[ [ 'AB', 1 ], [ 'CD', 2 ], [ 'EF', 3 ], [ 'GH', 3 ] ]