我有一组数字,我需要确保它们是唯一的。我在互联网上找到了下面的代码片段,它工作得很好,直到数组中有一个零。我在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数组中删除重复值
类似的问题:
获取数组中的所有非唯一值(即:重复/多次出现)
可以使用“集”消除重复项。
const originalNumbers = [1, 2, 2, 3, 3, 4, 4, 4, 4, 5, 1, 2, 9];
const uniqueNumbersSet = new Set(originalNumbers);
/** get the array back from the set */
const uniqueNumbersArray = Array.from(uniqueNumbersSet);
/** uniqueNumbersArray outputs to: [1, 2, 3, 4, 5, 9] */
了解有关集合的更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
使用ES6(一个衬垫)
基元值数组
let originalArr= ['a', 1, 'a', 2, '1'];
let uniqueArr = [...new Set(originalArr)];
对象阵列
let uniqueObjArr = [...new Map(originalObjArr.map((item) => [item["propertyName"], item])).values()];
const ObjArray = [
{
name: "Eva Devore",
character: "Evandra",
episodes: 15,
},
{
name: "Alessia Medina",
character: "Nixie",
episodes: 15,
},
{
name: "Kendall Drury",
character: "DM",
episodes: 15,
},
{
name: "Thomas Taufan",
character: "Antrius",
episodes: 14,
},
{
name: "Alessia Medina",
character: "Nixie",
episodes: 15,
},
];
let uniqueObjArray = [...new Map(ObjArray.map((item) => [item["id"], item])).values()];
您也可以使用sugar.js:
[1,2,2,3,1].unique() // => [1,2,3]
[{id:5, name:"Jay"}, {id:6, name:"Jay"}, {id: 5, name:"Jay"}].unique('id')
// => [{id:5, name:"Jay"}, {id:6, name:"Jay"}]