How to use Array.prototype.every() In Typescript

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


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()

Similar Reads

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....

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....

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....

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....