![]() |
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
Approach 1: Using TypeScript filter() MethodThe filter() method creates a new array of elements that matches the passed condition through the callback function. It will include only those elements for which true is returned. Example: The below code uses the filter() method to remove duplicate of an element in TypeScript array.
Output: [ 1, 2, 3, 4, 5, 6] Approach 2: Using TypeScript reduce() MethodThe 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.
Output: [ 1, 2, 3, 4, 5, 6] Approach 3: Using TypeScript set() MethodThis method sets a new object type that allows you to create collections of unique values. Example: This example uses the TypeScript set() method to remove duplicates from an array.
Output: [ 1, 2, 3, 4, 5, 6] Approach 4: Using TypeScript indexOf() MethodThe indexOf() method is used to find the first index of occurrence of an array element. we can iterate over the elements in the array, and we will push into the new array if it doesn’t exist in the resultant array. Example: The below code example uses the indexOf() method method to remove duplicates from an array in TypeScript.
Output: [ 1, 2, 3, 4, 5, 6] Approach 5: Using TypeScript forEach() MethodBy using the forEach() method, we can iterate over the elements in the array, and we will push into the new array if it doesn’t exist in the array. Example: The forEach() method is used to remove the elements from the TypeScript array in the below code.
Output: [ 1, 2, 3, 4, 5, 6] Approach 6: Using TypeScript MapThe Map object holds key-value pairs and remembers the original insertion order of the keys. We can leverage this feature to remove duplicates from an array. Example: In the following example, we utilize a Map to remove duplicate elements from a TypeScript array.
Output: [1, 2, 3, 4, 5, 6] Approach 7: Using TypeScript Sort() and Reduce() Methods TogetherAnother approach to remove duplicates from an array in TypeScript involves first sorting the array and then using the reduce() method to filter out the duplicates. This method can be efficient, especially for large arrays, as it reduces the complexity by ensuring only adjacent elements need to be compared. Example: The below code uses the sort() and reduce() methods together to remove duplicates from a TypeScript array.
Output: [ 1, 2, 3, 4, 5, 6 ] |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 11 |