配列の値がすべて等しいか確認
const isAllEqual = array => array.every(value => value === array[0]);
指定した配列の値がすべて等しい場合にtrue
を返します。
配列の値がすべて等しいを言い換えるとすべての値が配列の先頭値と同じということなので、それをevery()
を用いて確認します。
const colors01 = ['red', 'blue', 'yellow'];
const colors02 = ['red', 'blue', 'blue', 'yellow', 'red', 'yellow'];
const colors03 = ['red', 'red', 'red', 'red', 'red'];
const isAllEqual = array => array.every(value => value === array[0]);
isAllEqual(colors01); // false
isAllEqual(colors02); // false
isAllEqual(colors03); // true
配列の値がすべて等しくないか確認
const isAllUnique = array => array.length === new Set(array).size;
上とは逆で、指定した配列の値がすべて等しくない場合にtrue
を返します。
length
で取得した要素数とSet
オブジェクトで重複を削除後にsize
で取得した要素数とを比較します。
const colors01 = ['red', 'blue', 'yellow'];
const colors02 = ['red', 'blue', 'blue', 'yellow', 'red', 'yellow'];
const colors03 = ['red', 'red', 'red', 'red', 'red'];
const isAllUnique = array => array.length === new Set(array).size;
isAllUnique(colors01); // true
isAllUnique(colors02); // false
isAllUnique(colors03); // false