DEV Community

loading...
Cover image for TypeScript - Check if an array contains only unique values

TypeScript - Check if an array contains only unique values

shane profile image shane ・1 min read

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))
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

As a one liner

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

As a function

onlyUnique(values: Array<any>): boolean {
  return (Array.from(new Set(values)).length === values.length);
}
Enter fullscreen mode Exit fullscreen mode

Now follow me on twitter plz https://twitter.com/theshanemcgowan

Discussion (1)

Collapse
raulcg profile image
RaulC-G • Edited

another way:

function uniques (
item: T,
index: number,
array: any[]
) : T { return array.indexOf(item) == index); }

function everyIsUnique (array : any[]) : boolean {
return array.filter(uniques).length == array.length
}

Forem Open with the Forem app