Check if All Array Items Are Equal in JavaScript
- 1 minute read
The following JavaScript function returns true
if each item in the passed array is of a matching type and value:
// Same value, same type
const isUniform = (array) => {
const firstItem = array[0];
return array.every((item) => item === firstItem);
};
isUniform([`a`, `b`, `c`]); // returns false
isUniform([`a`, `a`, `a`]); // returns true
Otherwise, it returns false
.
And the following modified isUniform
function serves the same function, except it does not check for matching types, and only checks for matching values:
// Same value, arbitrary type
const isUniform = (array) => {
const firstItem = array[0];
return array.every((item) => item == firstItem);
};
isUniform([`1`, 2, 3]); // returns false
isUniform([1, 2, 3]); // returns false
isUniform([`1`, 1, 1]); // returns true
isUniform([1, 1, 1]); // returns true
The only difference between the above two snippets is the equality operators used in the every() array method, which performs the same test on each item in a given array.
Conclusion
This is the quickest and simplest way I’ve found to check whether every item in a JavaScript array is of the same value. I hope it helps you out!