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

类似的问题:

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


当前回答

也可以使用jQuery

var a = [1,5,1,6,4,5,2,5,4,3,1,2,6,6,3,3,2,4];

// note: jQuery's filter params are opposite of javascript's native implementation :(
var unique = $.makeArray($(a).filter(function(i,itm){ 
    // note: 'index', not 'indexOf'
    return i == $(a).index(itm);
}));

// unique: [1, 5, 6, 4, 2, 3]

最初的答案是:jQuery函数从数组中获取所有唯一元素?

其他回答

很多人已经提到使用。。。

[...new Set(arr)];

这是一个很好的解决方案,但我的首选是与.filter一起使用的解决方案。在我看来,filter是获取唯一值的更自然的方法。您可以有效地删除重复项,而从数组中删除元素正是过滤器的作用所在。它还允许您链接.map、.reduce和其他.filter调用。我设计了这个解决方案。。。

const unique = () => {
  let cache;  
  return (elem, index, array) => {
    if (!cache) cache = new Set(array);
    return cache.delete(elem);
  };
};

myArray.filter(unique());

需要注意的是,你需要一个结束,但我认为这是一个值得的权衡。就性能而言,它比我看到的使用.filter的其他解决方案更具性能,但比[…new Set(arr)]性能更差。

另请参阅我的github包

这已经得到了很多回答,但并没有解决我的特殊需求。

许多答案是这样的:

a.filter((item, pos, self) => self.indexOf(item) === pos);

但这对复杂对象的数组不起作用。

假设我们有一个这样的数组:

const a = [
 { age: 4, name: 'fluffy' },
 { age: 5, name: 'spot' },
 { age: 2, name: 'fluffy' },
 { age: 3, name: 'toby' },
];

如果我们想要具有唯一名称的对象,我们应该使用array.prototype.findIndex而不是array.protoype.indexOf:

a.filter((item, pos, self) => self.findIndex(v => v.name === item.name) === pos);

如前所述,[…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(唯一);

使用猫鼬,我有一组ObjectId可以使用。

我有一个要处理的对象ID的数组/列表,首先需要将其设置为字符串,然后在唯一集之后,修改回对象ID。

var mongoose=要求('mongoose')var ids=[ObjectId(“1”),ObjectId(“2”),ObjectId(“3”)]var toStringIds=ids.map(e=>“”+e)let uniqueIds=[…new Set(toStringIds)]uniqueIds=uniqueIds.map(b=>mongoose.Types.ObjectId(b))console.log(“uniqueIds:”,uniqueIds)

如果您想删除重复项,返回整个对象,并希望使用ES6 Set and Map语法,并且只运行一个循环,您可以尝试这样做,以获得唯一的ID:

常量集合=〔{id:3,名称:“A”},{id:4,名称“B”}、{id:6,名称为“C”};{id:5,名称是“D”}〕函数returnUnique(itemsCollection){const itemsMap=新映射();itemsCollection.forEach(item=>{如果(itemsMap.size==0){itemsMap集(item.id,项)}否则如果(!itemsMap.has(item.id)){itemsMap集(item.id,项)}});return[…new Set(itemsMap.values())];}console.log(returnUnique(集合));