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

类似的问题:

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


当前回答

(函数(){“使用严格”;Array.prototype.unique=函数unique(){var self=this;返回自滤波器(函数(a){var=this;//console.log(那个);回来那是什么?[a]=真:假;}, {});}var sampleArray=[0,1,2,3,4,5,6,7,8,9,0,1,4,2,6,4,8,9];var distinctArray=sampleArray.unique();console.log(distinctArray);})();下面是解决这个问题的简单方法。。。

其他回答

[...new Set(duplicates)]

这是从MDN Web文档中引用的最简单的一个。

const numbers = [2,3,4,4,2,3,3,4,4,5,5,6,6,7,5,32,3,4,5]
console.log([...new Set(numbers)]) // [2, 3, 4, 5, 6, 7, 32]

这是因为0在JavaScript中是一个错误的值。

如果数组的值为0或任何其他错误值,则此[i]将是错误的。

也可以使用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函数从数组中获取所有唯一元素?

如果您对额外的依赖关系感到满意,或者您的代码库中已经有一个库,那么可以使用LoDash(或Undercore)从阵列中删除重复项。

用法

如果您的代码库中还没有它,请使用npm安装它:

npm install lodash

然后按如下方式使用:

import _ from 'lodash';
let idArray = _.uniq ([
    1,
    2,
    3,
    3,
    3
]);
console.dir(idArray);

输出:

[ 1, 2, 3 ]

这是一个ES6函数,它从对象数组中删除重复项,并按指定的对象属性进行筛选

function dedupe(arr = [], fnCheck = _ => _) {
  const set = new Set();
  let len = arr.length;

  for (let i = 0; i < len; i++) {
    const primitive = fnCheck(arr[i]);
    if (set.has(primitive)) {
      // duplicate, cut it
      arr.splice(i, 1);
      i--;
      len--;
    } else {
      // new item, add it
      set.add(primitive);
    }
  }

  return arr;
}

const test = [
    {video:{slug: "a"}},
    {video:{slug: "a"}},
    {video:{slug: "b"}},
    {video:{slug: "c"}},
    {video:{slug: "c"}}
]
console.log(dedupe(test, x => x.video.slug));

// [{video:{slug: "a"}}, {video:{slug: "b"}}, {video:{slug: "c"}}]