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

类似的问题:

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


当前回答

我想从对象数组中删除重复项。重复项具有相同的ID。这是我所做的。

// prev data
const prev = [
  {
    id: 1,
    name: "foo",
  },
  {
    id: 2,
    name: "baz",
  },
  {
    id: 1,
    name: "foo",
  },
];

// method:
// Step 1: put them in an object with the id as the key. Value of same id would get overriden.
// Step 2: get all the values.

const tempObj = {};
prev.forEach((n) => (tempObj[n.id] = n));
const next = Object.values(tempObj);

// result
[
  {
    id: 1,
    name: "foo",
  },
  {
    id: 2,
    name: "baz",
  }
];

其他回答

奇怪的是,这以前没有人提出过。。要按数组中的对象键(下面的id)删除重复项,可以执行以下操作:

const uniqArray = array.filter((obj, idx, arr) => (
  arr.findIndex((o) => o.id === obj.id) === idx
)) 

你可以试试这个:

function removeDuplicates(arr){
  var temp = arr.sort();
  for(i = 0; i < temp.length; i++){
    if(temp[i] == temp[i + 1]){
      temp.splice(i,1);
      i--;
    }
  }
  return temp;
}

对我来说,这是最简单的解决方案

//检查数组是否相等的方法常量a=['a','B','C'].sort().toString()常量b=['A','C','b'].sort().toString()console.log(a===b);//真的//测试用例常量数据=[{组:“A”,名称:“SD”},{组:“B”,名称:“FI”},{组:“A”,名称:“SD”},{组:“B”,名称:“CO”}];//返回一个不带重复定位的新数组函数唯一(数据){return data.reduce(函数(累加器,currentValue){//转换为字符串以检查它们是否为相同的值。const currentKeys=对象.keys(currentValue).sort().toString();const currentValues=对象.values(currentValue).sort().toString();let hasObject=falsefor(累加器的常量对象){//将键和值转换为字符串,以便我们可以//看看它们是否与当前值相等constkeys=对象.keys(obj).sort().toString();const values=Object.values(obj).sort().toString();//检查键和值是否相等if(keys==currentKeys&&values==currentValues){hasObject=真}}//如果对象不存在,则推送该对象。if(!hasObject){累加器推力(currentValue)}回流蓄能器}, []);}//运行测试用例console.log(唯一(数据));//[{组:“A”,名称:“SD”},{组为“B”,名称为“FI”}、{组“B”、名称为“CO”}]

Array.prototype.getUnique = function() {
    var o = {}, a = []
    for (var i = 0; i < this.length; i++) o[this[i]] = 1
    for (var e in o) a.push(e)
    return a
}

在简单方法中查找唯一的数组值

function arrUnique(a){
  var t = [];
  for(var x = 0; x < a.length; x++){
    if(t.indexOf(a[x]) == -1)t.push(a[x]);
  }
  return t;
}
arrUnique([1,4,2,7,1,5,9,2,4,7,2]) // [1, 4, 2, 7, 5, 9]