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

类似的问题:

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


当前回答

使用猫鼬,我有一组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)

其他回答

看看这个。Jquery提供uniq方法:https://api.jquery.com/jQuery.unique/

var ids_array = []

$.each($(my_elements), function(index, el) {
    var id = $(this).attr("id")
    ids_array.push(id)
});

var clean_ids_array = jQuery.unique(ids_array)

$.each(clean_ids_array, function(index, id) {
   elment = $("#" + id)   // my uniq element
   // TODO WITH MY ELEMENT
});

使用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的评论提示。

对于字符串数组:

function removeDuplicatesFromArray(arr) {
  const unique = {};
  arr.forEach((word) => {
    unique[word] = 1; // it doesn't really matter what goes here
  });
  return Object.keys(unique);
}

你根本不需要.indexOf();你可以这样做O(n):

function SelectDistinct(array) {
    const seenIt = new Set();

    return array.filter(function (val) {
        if (seenIt.has(val)) { 
            return false;
        }

        seenIt.add(val);

        return true;
    });
}

var hasDuplicates = [1,2,3,4,5,5,6,7,7];
console.log(SelectDistinct(hasDuplicates)) //[1,2,3,4,5,6,7]

如果不想使用.filter():

function SelectDistinct(array) {
    const seenIt = new Set();
    const distinct = [];

    for (let i = 0; i < array.length; i++) {
        const value = array[i];

        if (!seenIt.has(value)) {
            seenIt.add(value);
            distinct.push(value);
        }
    }
    
    return distinct; 
    /* you could also drop the 'distinct' array and return 'Array.from(seenIt)', which converts the set object to an array */
}

在ES6/以后

仅获取唯一值

  let a = [
           { id: 1, name: "usman" },
           { id: 2, name: "zia" },
           { id: 3, name: "usman" },
          ];
const unique = [...new Set(a.map((item) => item.name))];
console.log(unique); // ["usman", "zia"]

获取唯一对象

const myObjArray = [
                       { id: 1, name: "usman" },
                       { id: 2, name: "zia" },
                       { id: 3, name: "usman" },
                   ];
// Creates an array of objects with unique "name" property values.
let uniqueObjArray = [
  ...new Map(myObjArray.map((item) => [item["name"], item])).values(),
];

console.log("uniqueObjArray", uniqueObjArray);