我有一组数字,我需要确保它们是唯一的。我在互联网上找到了下面的代码片段,它工作得很好,直到数组中有一个零。我在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数组中删除重复值
类似的问题:
获取数组中的所有非唯一值(即:重复/多次出现)
使用Set删除重复项。
具有重复项的阵列
const withDuplicates = [2, 2, 5, 5, 1, 1, 2, 2, 3, 3];
使用Set获取不重复的新数组
const withoutDuplicates = Array.from(new Set(withDuplicates));
较短版本
const withoutDuplicates = [...new Set(withDuplicates)];
结果:[2,5,1,3]
你根本不需要.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 */
}
要删除重复项,可能有两种情况。首先,所有数据都不是对象,其次所有数据都是对象。
如果所有数据都是任何类型的原始数据类型,如int、float、string等,那么您可以遵循以下一种
const uniqueArray = [...new Set(oldArray)]
但假设您的数组包含以下JS对象
{
id: 1,
name: 'rony',
email: 'rony@example.com'
}
然后,要获取所有唯一的对象,可以执行以下操作
let uniqueIds = [];
const uniqueUsers = oldArray.filter(item => {
if(uniqueIds.includes(item.id)){
return false;
}else{
uniqueIds.push(item.id);
return true;
}
})
您也可以使用此方法使任何类型的数组成为唯一的。只需将跟踪键保留在uniqueIds数组上。
任务是从由任意类型(基元和非基元)组成的数组中获取唯一的数组。
基于使用新集合(…)的方法不是新的。这里它被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”]*/
使用ES6新设置
变量数组=[3,7,5,3,2,5,2,7];var unique_array=[…新集合(数组)];console.log(unique_array);//输出=[3,7,5,2]
使用For循环
变量数组=[3,7,5,3,2,5,2,7];for(var i=0;i<array.length;i++){for(变量j=i+1;j<array.length;j++){如果(array[i]===array[j]){阵列.拼接(j,1);}}}console.log(数组);//输出=[3,7,5,2]