Coding - JS utils
Unique Array

Unique Array

Difficulty: Easy, Duration: 10 minutes, Languages: JS, TS, Author: Kiran Dash (opens in a new tab)

Question

Create a function uniqueArray, which can be used to create a new array with unique elements from an existing array.

Example

example.ts
uniqueArray([2, 1, 2]); // [2, 1]

Launch exercise in editor (opens in a new tab)

Solution

Brute force with Array.prototype.indexOf()

solution.ts
export default function uniqueArray(input: Array<number>): Array<number> {
  const uniqueElements = [];
  for (let elem of input) {
    if (uniqueElements.indexOf(elem) === -1) {
      uniqueElements.push(elem);
    }
  }
  return uniqueElements;
}

Time Complexity: O(n^2) since Array.prototype.indexOf() is an O(n) operation

Brute force with Array.prototype.includes()

solution.ts
export default function uniqueArray(input: Array<number>): Array<number> {
  const uniqueElements = [];
  for (let elem of input) {
    if (!uniqueElements.includes(elem)) {
      uniqueElements.push(elem);
    }
  }
  return uniqueElements;
}

Time Complexity: O(n^2) since Array.prototype.includes() is an O(n) operation

Launch Solution in Editor (opens in a new tab)

Tracking elements with Set 🔥

Instead of Array.prototype.includes(), we can use Set.prototype.has() to check for existence of an element with O(1) time complexity

solution.ts
export default function uniqueArray(input: Array<number>): Array<number> {
  const uniqueElements = [];
  const seenElements = new Set();
 
  for (let elem of input) {
    if (!seenElements.has(elem)) {
      uniqueElements.push(elem);
      seenElements.add(elem);
    }
  }
 
  return uniqueElements;
}

Time Complexity: O(n)

Launch Solution in Editor (opens in a new tab)

Convert to Set and back to Array

solution.ts
export default function uniqueArray(input: Array<number>): Array<number> {
  return Array.from(new Set(input));
}

Time Complexity: O(n)

Launch Solution in Editor (opens in a new tab)

Resources