typescript -配列が一意の値のみを含むかどうかを調べる



イントロ
タイプスクリプトの中のクールなトリックは、配列から非一意の値を取り除くためにSetを使うことができます.これをArray.fromと結合してください、そして、あなたは何もユニークな値を除去するために速い1ライナーを得ます
const unqiueValues = Array.from(new Set(YOUR_ARRAY_HERE))

一歩一歩
// 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)

ワンライナーとして
const values = [0,0,1,'a','a','b','c'];
const unique = (Array.from(new Set(values)).length === values.length);

機能として
onlyUnique(values: Array<any>): boolean {
  return (Array.from(new Set(values)).length === values.length);
}
さあ、Twitter PLUSでフォローして