Check if all values of an array are equal
Quickly check array equality with every()
:
Try it out:
This one-liner uses the Array.prototype.every
method for efficient equality checking.
Every, Set, or Reduce? Choose your fighter!
Using every()
for checking equality
The every()
method checks if all elements in your array meet the condition stated in your function (here, equality to the first element).
The uniqueness of Sets
If the array's values show a high level of sameness, Set
is your hero:
Since a Set
stores unique values only, you'll get a set size of 1
for an array with identical values.
Reduce: An eccentric choice
For lovers of the reduce
method, here's your play:
Watch out for the TypeError
if the array is empty. Also, Boolean casting clarifies your outcome.
Custom prototype method: For reusable checks
Craft your own array prototype method:
This makes the check available for all array instances in your project. Remember, with great power comes great responsibility!
Performance considerations: Which horse to bet on?
.every()
- Fast. Furious.
.every()
gives you results "fast and furious". As soon as an unequal element is found, it finishes its run, making it efficient especially for large arrays.
Set
- The unique champion
Set
is a strong player when dealing with massive arrays filled with mostly identical items and where position may vary.
Extra gear: Edge cases and specialities
Empty arrays and the truth
Empty arrays are tricky in JavaScript, they're truthy. Always add sanity checks to prevent surprises.
Falsy values and NaN: Your weird cousins
With NaN
or Falsy
values, use the ===
operator. NaN
is not equal to NaN
, and Falsy
values could give unexpected results with loose equality checks.
Cast away with !!
Use !!
to make sure the result is a boolean:
Was this article helpful?