Explain Codes LogoExplain Codes Logo

Check if all values of an array are equal

javascript
functions
promises
callbacks
Alex KataevbyAlex Kataev·Nov 18, 2024
TLDR

Quickly check array equality with every():

const allEqual = arr => arr.every(v => v === arr[0]);

Try it out:

console.log(allEqual([1, 1, 1])); // "I guess they liked the number 1", prints true

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

const allEqual = arr => arr.every(v => v === arr[0]);

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:

const allEqual = arr => new Set(arr).size === 1;

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:

const allEqual = arr => arr.length === 0 || arr.reduce((a,b) => a === b ? a : false) !== false;

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:

Array.prototype.allEqual = function() { return new Set(this).size === 1; };

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:

const allEqual = arr => !!arr.reduce((a, b) => a === b ? a : false, arr[0]);