home / blog May 28th, 2021

TypeScript - Check if an array contains only unique values

Quick guide on how to check if an array in TypeScript contains only unique values

Intro

A cool trick in TypeScript is that you can use a Set to remove nonunique values from an array. Combine this with Array.from and you get a quick one liner to remove none unique values

const unqiueValues = Array.from(new Set(YOUR_ARRAY_HERE))

Step by Step

  // Our array of non unique values
  const values = [0,0,1,'a','a','b','c'];
  
  // Create a `Set` from our array
  // Sets can only contain unique values so duplicate will be removed for us
  const uniqueSet = new Set(values);
  
  // Create a new array from our set so we can use the Array.length property
  const unqiueValues = Array.from(uniqueSet);
  
  // Compare the length of the original `values` array and the new `uniqueValues` array
  // If the lengths differ then a non unique value was removed by the set
  // This means that the original array contained non-unique values
  const isUnique = (values.length === unqiueValues.length)

As a one liner

const values = [0,0,1,'a','a','b','c'];
const unique = (Array.from(new Set(values)).length === values.length);

As a function

onlyUnique(values: Array): boolean {
  return (Array.from(new Set(values)).length === values.length);
}