find duplicates in Array<number> typescript
- User
find duplicates in Array typescript
- Assistant
To find duplicates in an array of numbers in TypeScript, you can use a combination of a JavaScript
Setor aMapto track occurrences of each element. Below is an example using aSet:function findDuplicates(arr: number[]): number[] { const seen = new Set<number>(); const duplicates = new Set<number>(); for (const num of arr) { if (seen.has(num)) { duplicates.add(num); } else { seen.add(num); } } return Array.from(duplicates); } // Example usage: const numbers = [1, 2, 3, 4, 2, 5, 6, 1, 7, 8, 3]; const duplicates = findDuplicates(numbers); console.log(duplicates); // Output: [1, 2, 3]Explanation:
-
Set: ASetis used to keep track of numbers that have already been seen as you iterate through the array. Theaddoperation for is constant time on average, making this an efficient approach.
-
- User
rewrite this code using lodash
- Assistant
To find duplicates in an array of numbers using lodash, you can leverage lodash's utility functions to make the code more concise and readable. Here's how you can do it:
import _ from 'lodash'; function findDuplicates(arr: number[]): number[] { // Use lodash's countBy to count occurrences of each number const occurrences = _.countBy(arr); // Filter those numbers which occur more than once const duplicates = _.keys(_.pickBy(occurrences, count => count > 1)).map(Number); return duplicates; } // Example usage: const numbers = [1, 2, 3, 4, 2, 5, 6, 1, 7, 8, 3]; const duplicates = findDuplicates(numbers); console.log(duplicates); // Output: [1, 2, 3]Explanation:
-
_.countBy(arr): This function creates an object with the numbers as keys and their occurrences as values. -
_.pickBy: Filters the object created bycountByto include only those entries where the count is greater than 1, which indicates duplicates. -
Extracts the keys (the numbers) from the filtered object, and converts those string keys back to numbers.
-