typescript -配列が一意の値のみを含むかどうかを調べる
5215 ワード
イントロ
タイプスクリプトの中のクールなトリックは、配列から非一意の値を取り除くために
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でフォローしてReference
この問題について(typescript -配列が一意の値のみを含むかどうかを調べる), 我々は、より多くの情報をここで見つけました https://dev.to/shane/typescript-check-if-an-array-contains-only-unique-values-3b3eテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol