Code Logo

Unique Values with Set<number>

Published at25 Jul 2026
TypeScript Collections Easy 0 views
Like0

Write a TypeScript function that takes an array of numbers and returns a new array containing only unique values using Set. The Set type in TypeScript is generic: Set ensures all elements have type T at compile time.

TypeScript's generic syntax Set specifies that this set can only hold number values. This is different from JavaScript where a Set can hold mixed types. The type parameter is checked at compile time and erased at runtime, providing type safety without runtime overhead.

Converting a Set back to an array uses the spread operator [...set] or Array.from(set). TypeScript infers the resulting array type as number[] from the Set type, maintaining type safety throughout the operation.

Time complexity is O(n) where n is the input length. Set operations are O(1) average for add and has. Space complexity is O(k) where k is the number of unique elements.

Edge cases include empty arrays, arrays with all duplicates, arrays with all unique values, and ensuring the function returns a new array without modifying the input.

Example Input & Output

Example 1
Input
[-1,0,-1]
Output
[-1,0]
Explanation

With negatives

Example 2
Input
[]
Output
[]
Explanation

Empty array

Example 3
Input
[1,2,3]
Output
[1,2,3]
Explanation

Already unique

Example 4
Input
[1,2,2,3,3,3]
Output
[1,2,3]
Explanation

Removes duplicates

Example 5
Input
[5,5,5]
Output
[5]
Explanation

All same values

Algorithm Flow

Recommendation Algorithm Flow for Unique Values with Set<number>
Recommendation Algorithm Flow for Unique Values with Set<number>

Solution Approach

function solution(nums: number[]): number[] {
  var seen: any = {};
  var res: number[] = [];
  for (var i = 0; i < nums.length; i++) {
    if (!seen[nums[i]]) { seen[nums[i]] = true; res.push(nums[i]); }
  }
  return res;
}

Best Answers

typescript - Approach 1
function solution(nums: number[]): number[] {
  var seen: any = {};
  var res: number[] = [];
  for (var i = 0; i < nums.length; i++) {
    if (!seen[nums[i]]) { seen[nums[i]] = true; res.push(nums[i]); }
  }
  return res;
}