How to useTypeScript reduce() Method in Typescript
The reduce() method is used to reduce the elements of the array and combine them into a final array based on some reducer function that you pass.
Example: The reduce() method is used to remove duplicates from an array in TypeScript.
let arr = [1, 2, 2, 3, 4, 3, 5, 4, 6, 5];
const removeDups = ( arr: number[]): number[] => {
let unique: number[] =
arr.reduce(function (acc: number[], curr: number) {
if (!acc.includes(curr))
acc.push(curr);
return acc;
}, []);
return unique;
}
console.log(removeDups(arr));
Output:
[ 1, 2, 3, 4, 5, 6]
Remove Duplicate Elements from TypeScript Array
TypeScript array is a single variable that is used to store the elements or a group of values of the same type. An array can contain multiple occurrences or duplicates of an element that can be removed using the below-discussed methods.
Below are the approaches used to remove Duplicate Elements from the TypeScript Array
Table of Content
- Using TypeScript filter() Method
- Using TypeScript reduce() Method
- Using TypeScript set() Method
- Using TypeScript indexOf() Method
- Using TypeScript forEach() Method
- Using TypeScript Map