If you have an array with primitive values as per below;
const arr = [1, 2, 3, 4, 45, 4, 66, 3];
Is there a more efficient way to check whether all the items are unique rather than iterating all items as below?
let newArr = [];
let isUnique = true;
arr.forEach(item =>
{
if(newArr.indexOf(item) != -1)
{
isUnique = false;
break;
}
newArray.push(item);
});
An indexOf
in a forEach
is O(n ^ 2)
. I'd use a Set instead - Set.has
is O(1)
(overall complexity of 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]));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.