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

类似的问题:

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


当前回答

现在使用集合,可以删除重复项并将其转换回数组。

var name=[“Mike”,“Matt”,“Nancy”,“马特”,“亚当”,“Jenny”,“南希”,“卡尔”];console.log([…新集(名称)])

另一种解决方案是使用排序和筛选

var name=[“Mike”,“Matt”,“Nancy”,“马特”,“亚当”,“Jenny”,“南希”,“卡尔”];var namesSorted=names.sort();常量结果=namesSorted.filter((e,i)=>namesSorted[i]!=名称排序[i+1]);console.log(结果);

其他回答

任务是从由任意类型(基元和非基元)组成的数组中获取唯一的数组。

基于使用新集合(…)的方法不是新的。这里它被JSON.stringify(…)、JSON.parse(…)和[].map方法所利用。其优点是通用性(适用于任何类型的数组)、简短的ES6表示法以及在这种情况下的性能:

常量重复数据消除示例=[{a:1},{a:1},[ 1, 2 ],[ 1, 2 ],1.1.'1','1']常量getUniqArrDeep=arr=>{const arrStr=arr.map(项=>JSON.stringify(项))return[…新集合(arrStr)].map(item=>JSON.parse(item))}console.info(getUniqArrDeep(重复数据消除示例))/*[{a:1},[1,2],1,“1”]*/

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

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

变量数=[1,1,2,3,4,4];函数唯一(dupArray){return dupArray.reduce(函数(上一个,num){if(previous.find(函数(项){返回项==num;})) {返回上一个;}其他{先前推送(num);返回上一个;}}, [])}var check=唯一(数字);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)

一种可扩展、快速、高效且易于阅读的现代方法,使用iter ops库:

import {pipe, distinct} from 'iter-ops';

const input = [1, 1, 2, 2, 2, 3]; // our data

const i = pipe(input, distinct()); // distinct iterable

console.log([...i]); //=> [1, 2, 3]

如果您的输入是一个对象数组,则只需为不同的运算符提供一个键选择器。