How to use a Set to Create the Function In Typescript
In this method, we create a Set from the array, which automatically removes duplicate values. After which we compares the size of the Set to the length of the original array. If they are different, then the array contains duplicates.
Syntax:
new Set(array_name).size !== array_name.length;
Example: The below code explains the use of the Set to create a function that checks for duplicates in an array.
function hasDuplicatesUsingSet(array: any[]):
void {
const mySet = new Set(array);
if (mySet.size !== array.length) {
console.log("The Array: [" + array +
"] contains duplicate elements.");
}
else {
console.log("The Array: [" + array +
"] does not contain duplicate elements.");
}
}
hasDuplicatesUsingSet([1, 2, 3, 4, 5]);
hasDuplicatesUsingSet([1, 2, 3, 4, 1]);
hasDuplicatesUsingSet(["GFG", "JavaScript", "GFG"]);
hasDuplicatesUsingSet(["GFG", "JavaScript"]);
Output:
The Array: [1,2,3,4,5] does not contain duplicate elements.
The Array: [1,2,3,4,1] contains duplicate elements.
The Array: [GFG,JavaScript,GFG] contains duplicate elements.
The Array: [GFG,JavaScript] does not contain duplicate elements.
How to Create a TypeScript Function to Check for Duplicates in an Array ?
We are given a TypeScript array and we have to create a TypeScript function that checks whether the given array contains duplicates or not.
Example:
Input: array1 = [1, 2, 3, 4, 5] Output: False Explantion: No duplicates in the array Input: array1 = [1, 2, 3, 4, 1] Output: True Explantion: 1 repeats two time in the array
Table of Content
- Using a Set to Create the Function
- Using Array.prototype.includes()
- Using Array.prototype.reduce()
- Using Array.prototype.every()