How to remove duplicates from an Array in TypeScript

In this article, we will learn how to remove duplicates from an Array in TypeScript.

Set Method

The simplest and most efficient way to remove duplicates from an array is using Set. A Set is a built-in function in a JavaScript object that stores unique values.

const setArray = new Set([1001,1020,1400,2300,1002]);
// Array.from Method

const Uniquevalue= Array.from(new Set(setArray));

// Spread Method
const Uniquevalue = [... new Set(setArray)];

console.log(Uniquevalue);

Output:

[1001, 1020, 1400, 2300, 1002]

Filter() Method

Using Filter with the ‘IndexOf’ array method, we can remove duplicates from the array object.

const Uniquevalue = [1001,1020,1400,2300,1002,6500,5001,4001,5001];
 
console.log('Filter Method'); 
const uniqueEmpcode = Uniquevalue.filter((value,index,items)=> items.indexOf(value)===index);
console.log(Uniquevalue);

Output:

[1001, 1020, 1400, 2300, 1002, 6500, 5001, 4001] 

reduce() Method

With the ‘reduce()’ method we can also remove the duplicate elements in the array.

console.log('Reduce Method');
const Uniquevalue = [1001,1020,1400,2300,1002,6500,5001,4001,5001];
 
const uniqueEmpcodereduce = Uniquevalue.reduce(
    (value,items)=> value.includes(items) ? value : [...value,items],       
    []);
console.log(uniqueEmpcodereduce);

Here is the Output:

[1001, 1020, 1400, 2300, 1002, 6500, 5001, 4001] 

More Article Convert Set into an Array in TypeScript

Leave a Reply

Your email address will not be published. Required fields are marked *