Open In App

How to Create a TypeScript Function to Check for Duplicates in an Array ?

Last Updated : 03 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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 Remove Duplicates from an Array of Objects using TypeScript ?
We are given an array of objects and we have to check if there are duplicate objects present in the array and remove the duplicate occurrences from it. Otherwise, return the array as it is. Examples of Removing Duplicates from an Array of Objects using TypeScript Table of Content Using filter() and findIndex() methodsUsing Set and Array.from() meth
4 min read
Syntax to create function overloading in TypeScript
Function Overloading: Function overloading is a feature of object-oriented programming where two or more functions can have the same name but different parameters and also the data types of all the parameters in different functions would be different as well . When a function name is overloaded with different jobs/ requirements it is thus referred
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 complex type structure. Table of Content Using the ty
2 min read
How to Create TypeScript Generic Function with Safe Type Matching ?
In TypeScript, generic functions offer a powerful tool for creating flexible and reusable code that can work with various data types. However, ensuring type safety is crucial to prevent runtime errors and maintain code reliability. These are the following approaches:Table of Content Using Type constraintsUsing Type inferenceUsing Type guardsUsing T
3 min read
How to Create a Union Type from Nested Array in TypeScript ?
TypeScript developers often encounter scenarios where they need to represent a value that could be one of several different types. TypeScript's union types provide a solution to this problem by allowing variables to hold values of multiple types. However, when dealing with nested arrays, each nested array might represent a different type, making it
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 last element of the stackempty() Method: This met
3 min read
How to Create an Array of Multiple Data Types in TypeScript ?
In TypeScript, you can not directly define an array as you usually define it in JavaScript. You need to explicitly type the array with a particular data type whose values can be stored inside it. The type of an array can be specified using the colon syntax followed by the data type (:type). You can also create arrays that can store values of multip
2 min read
How to Create a Typed Array from an Object with Keys in TypeScript?
In TypeScript, we can create a typed array from an object with keys by extracting the keys and then mapping them to the desired array type. This mainly makes sure that type of safety is preserved. Below are the approaches used to create a Typed Array from an Object with Keys in TypeScript: Table of Content Using Object.keys() and map methodUsing Ob
3 min read
How to Create Array of String in TypeScript ?
An array of strings in TypeScript is a variable that can hold multiple string values. It allows you to perform manipulation of multiple strings within a single variable. We can declare an array of strings in TypeScript in different ways as listed below. Table of Content Using Array LiteralUsing the Array ConstructorUsing the Array's push() MethodUs
3 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 PropertyUsing every() MethodUsing filter() methodUsing lengt
2 min read