How to use Array.prototype.reduce() In Typescript
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.
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
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()