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<any>): boolean {
return (Array.from(new Set(values)).length === values.length);
}
Now follow me on twitter plz https://twitter.com/theshanemcgowan
Discussion (3)
There's nothing of TS about this. Waste of time.
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
}
In order to use it, you shoul apply constraints for Array, because it can be only primitive values