How to Create a TypeScript Function to Check for Duplicates in an Array ?
Last Updated :
03 May, 2024
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
Using a Set to Create the Function
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.
JavaScript
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.
Using Array.prototype.includes()
In this method, we will iterate over each element of the array and checks if the array includes the same element later in the array (starting from the next index). If such an element is found, it returns true, indicating duplicates.
Syntax:
array.some((item, index) => array.includes(item, index + 1));
Example: The below code explains the use of Array.prototype.includes() to create a function that checks for duplicates in an array.
JavaScript
function hasDuplicatesUsingIncludes(array: any[]): void {
const isDuplicate = array.
some((item, index) => array.
includes(item, index + 1));
if (isDuplicate) {
console.log("The Array: [" + array +
"] contains duplicate elements.");
}
else {
console.log("The Array: [" + array +
"] does not contain duplicate elements.");
}
}
hasDuplicatesUsingIncludes([1, 2, 3, 4, 5]);
hasDuplicatesUsingIncludes([1, 2, 3, 4, 1]);
hasDuplicatesUsingIncludes(["GFG", "JavaScript", "GFG"]);
hasDuplicatesUsingIncludes(["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.
Using Array.prototype.reduce()
In this method, we initializes an empty object (counter
) to keep track of the count of each element and than we iterates over each element of the array and increment its count in the counter
object. If the count becomes greater than 1 for any element, it indicates duplicates, and the function returns true.
Example: The below code explains the use Array.prototype.reduce() with an object as a counter to check for duplicates in an array.
JavaScript
function hasDuplicatesUsingReduce
(array: any[]): boolean {
const counter:
{ [key: string]: number } = {};
for (const item of array) {
counter[item] =
(counter[item] || 0) + 1;
if (counter[item] > 1) {
return true;
}
}
return false;
}
console.log
(hasDuplicatesUsingReduce([1, 2, 3, 4, 5]));
console.log
(hasDuplicatesUsingReduce([1, 2, 3, 4, 1]));
console.log
(hasDuplicatesUsingReduce(["GFG", "JavaScript", "GFG"]));
console.log
(hasDuplicatesUsingReduce(["GFG", "JavaScript"]));
Output:
false
true
true
false
Using Array.prototype.every()
This approach utilizes the every() method to check if every element in the array is unique. It compares each element of the array with every other element to determine if there are any duplicates.
Syntax:
function hasDuplicatesUsingEvery(array: any[]): boolean {
return array.every((item, index) =>
array.indexOf(item) === index
);
}
Example: The following code demonstrates the use of the hasDuplicatesUsingEvery function to check for duplicates in an array.
JavaScript
function hasDuplicatesUsingEvery(array: any[]): boolean {
return array.every((item, index) =>
array.indexOf(item) === index
);
}
console.log(hasDuplicatesUsingEvery([1, 2, 3, 4, 5])); // Output: true
console.log(hasDuplicatesUsingEvery([1, 2, 3, 4, 1])); // Output: false
console.log(hasDuplicatesUsingEvery(["GFG", "JavaScript", "GFG"])); // Output: false
console.log(hasDuplicatesUsingEvery(["GFG", "JavaScript"])); // Output: true
Output:
true
false
false
true
Similar Reads
How to Convert a Dictionary to an Array in TypeScript ?
In TypeScript, converting a dictionary(an object) into an Array can be useful in scenarios where you need to work with the values in a more iterable and flexible manner. These are the following approaches: Table of Content Using Object.keys methodUsing Object.values methodUsing Object.entries method
3 min read
How to Define a Generic Type for an Array in TypeScript ?
Generics in TypeScript are a way to write reusable code that can work with different types of data. When it comes to defining generic types for arrays. TypeScript provides flexible options to ensure type safety while allowing for flexibility in the types of elements stored in the array. Table of Con
3 min read
How to Declare a Function that Throws an Error in TypeScript ?
In this article, we are going to declare the functions that throw errors in TypeScript. A function can throw an error if the logic is not correct or you can deliberately declare the function that always throws an error. A function can be created with the different return types with the required type
2 min read
How to Create a Generic Type Alias for a Generic Function in TypeScript ?
In TypeScript, it is possible to create a generic type alias for a generic function. A generic type alias provides a descriptive name for a function with generic parameters, making it easier to understand the code. It also makes the code reusable and readable especially when you are dealing with com
2 min read
Check if an Array is Empty or not in TypeScript
In TypeScript, while performing any operation on the array, it is quite important that there should be elements or data in the array, else no operation can be done. We can check whether the array contains the elements or not by using the below-listed methods: Table of Content Using length PropertyUs
2 min read
How to Convert a Set to an Array in TypeScript ?
A Set in TypeScript is used to create a particular type of list that does not contain duplicate elements. If any element is repeated more than once it will automatically remove the duplicate existence and consider it only once in the list. In this article, we will convert these types of lists into a
5 min read
How to Check if an Array Includes an Object in TypeScript ?
In TypeScript, checking if an array includes an object consists of comparing the object's properties within the array elements. We can compare and check this using three different approaches some method, find method, and includes method. There are several ways to check if an array includes an object
3 min read
How to Create a Stack in TypeScript using an Array ?
Stack is a linear Data Structure that is based on the LIFO concept (last in first out). There are 5 primary operations in the stack as follows:push method(): This method adds element x to the stack.pop() Method: This method removes the last element of the stack.peek() Method: This method returns the
3 min read
How to use Optional Chaining with Arrays and Functions in TypeScript ?
In this article, we will learn how we can use optional chaining with arrays and functions in TypeScript. Optional chaining in Typescript is mainly a feature that allows us to safely access the properties or the call functions on potentially null or undefined values without causing any runtime errors
3 min read
How to Declare an Empty Array in TypeScript?
TypeScript provides a robust type system that allows you to define and manage data structures more effectively than in plain JavaScript. One common task is declaring empty arrays with specific types, ensuring that your array holds only values of the intended type. These are the following ways to dec
2 min read