You can use set size if all you need is to check if there has been duplicates added:
function hasDuplicates<T>(arr: T[]): boolean {
return new Set(arr).size < arr.length;
}
hasDuplicates(["A", "A"]) // true
hasDuplicates(["A", "B"]) // false
You can also use the proxy object to know when duplicate is added as they get added to the array:
const myArray1 = ["a", "b"];
const myArrayProxy1 = new Proxy(myArray1, {
set: (target, property, value) => {
const exits = target.includes(value);
if (exits) {
console.log(`Duplicate index ${property.toString()}, value: ${value}`);
}
return true;
}
});
myArrayProxy1.push("a", "a", "b", "c");
// Prints:
// Duplicate index 2, value: a
// Duplicate index 3, value: a
// Duplicate index 4, value: b
If you do want to want to be proactive and just work with your array without it having duplicates you can override the setting logic:
const myArray2 = ["a", "b"];
const myArrayProxy2 = new Proxy(myArray2, {
get: (target, property) => {
return Reflect.get(target.filter(Boolean), property);
},
set: (target, property, value) => {
const exits = target.includes(value);
return exits ? true : Reflect.set(target, property, value);
}
});
myArrayProxy2.push("a", "a", "b", "c");
console.log([...myArrayProxy2]); // - Prints: ["a", "b", "c"]
trueif the array contains duplicates andfalseif it doesn't. The question doesn't ask how to prevent duplicates from being added.