![](/img/trans.png)
[英]How to check whether specific items inside an array have a value? Javascript
[英]How to check whether the items are unique in an array using JavaScript
如果您有一個具有原始值的數組,如下所示;
const arr = [1, 2, 3, 4, 45, 4, 66, 3];
有沒有更有效的方法來檢查所有項目是否唯一,而不是如下迭代所有項目?
let newArr = [];
let isUnique = true;
arr.forEach(item =>
{
if(newArr.indexOf(item) != -1)
{
isUnique = false;
break;
}
newArray.push(item);
});
forEach
的indexOf
是O(n ^ 2)
。 我會改用 Set - Set.has
是O(1)
( O(n)
整體復雜度):
const allAreUnique = (arr) => {
const set = new Set();
for (const item of arr) {
if (set.has(item)) return false;
set.add(item);
}
return true;
};
const allAreUnique = (arr) => { const set = new Set(); for (const item of arr) { if (set.has(item)) return false; set.add(item); } return true; }; console.log(allAreUnique([1, 2, 3, 4, 45, 4, 66, 3])); console.log(allAreUnique([1, 2, 3, 4, 45, 66]));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.