How to Check if All Values in an Array are Equal in JavaScript
A common task in data validation is to check if every element in an array is identical. For example, you might want to verify that all items in a list have the same status or that all values are consistent. JavaScript provides several elegant, modern ways to perform this check.
This guide will teach you the two most effective methods for solving this problem. You will learn how to use the readable Array.prototype.every() method and the concise and clever approach using a Set object.
The Core Task: Comparing Every Element to the First
The logic for this check is simple: if all elements in an array are equal, then every single element must be equal to the first element. This simple observation is the foundation of our most readable solution.
Method 1 (Recommended for Readability): Array.prototype.every()
The .every() method is the perfect tool for this job. It tests whether every element in an array passes a test you provide.
The logic:
- We can iterate through the array and check if each
elementis strictly equal (===) to thearray[0](the first element).
The solution:
function allElementsAreEqual(array) {
// Check if the array is empty, which is a special case
if (array.length === 0) {
return true; // Or false, depending on your use case
}
return array.every(element => {
return element === array[0];
});
}
// ✅ Examples that return true
console.log(allElementsAreEqual([1, 1, 1])); // Output: true
console.log(allElementsAreEqual(['a', 'a', 'a'])); // Output: true
console.log(allElementsAreEqual([])); // Output: true
// ⛔️ Examples that return false
console.log(allElementsAreEqual([1, 2, 1])); // Output: false
console.log(allElementsAreEqual(['a', 'b'])); // Output: false
Method 2 (Recommended for Conciseness): Using a Set
A Set is a special JavaScript collection that only stores unique values. This property provides a very clever and concise way to check if all elements in an array are the same.
The logic:
- Create a
Setfrom the array. This will automatically remove all duplicate elements. - Check the
.sizeof the resultingSet. - If the size is
1or0, it means all the elements in the original array were identical.
The solution:
function allElementsAreEqual(array) {
// A new Set will only contain the unique elements from the array
const uniqueElements = new Set(array);
// If all elements are the same, the set's size will be 1 (or 0 if empty)
return uniqueElements.size <= 1;
}
// ✅ Examples that return true
console.log(allElementsAreEqual([1, 1, 1])); // Output: true
console.log(allElementsAreEqual(['a', 'a', 'a'])); // Output: true
console.log(allElementsAreEqual([])); // Output: true
// ⛔️ Examples that return false
console.log(allElementsAreEqual([1, 2, 1])); // Output: false
console.log(allElementsAreEqual(['a', 'b'])); // Output: false
This can be written as a very concise one-liner: const allEqual = arr => new Set(arr).size <= 1;
How the Methods Work
.every(): This method iterates through the array. If the callback function returnsfalsefor any element,.every()immediately stops and returnsfalse. If it gets through the entire array with the callback always returningtrue, then.every()returnstrue. This makes it very efficient, as it stops as soon as it finds a mismatch.new Set(): When you create aSetfrom an array, theSetconstructor iterates through the array and adds each element. Since aSetcannot contain duplicates, only the first occurrence of each unique value is kept. If the original array was[5, 5, 5], the resultingSetwould be{5}, and its.sizewould be1. If the array was[5, 5, 6], theSetwould be{5, 6}, and its.sizewould be2.
Handling Empty Arrays: An Important Edge Case
How should an empty array be treated?
[].every(...)returnstruefor any condition.new Set([]).sizeis0.
Both methods, as written, will return true for an empty array. This is often the desired behavior. If you consider an empty array to be a case where "not all elements are equal," you must add an explicit check for it.
function allElementsAreEqual(array) {
if (array.length === 0) {
return false; // Or handle as an invalid case
}
return new Set(array).size === 1;
}
Conclusion
Checking if all elements in an array are equal is a simple task with modern JavaScript's powerful built-in methods.
The key takeaways are:
- The
Array.prototype.every()method is the most readable and explicit solution. You check if every element is strictly equal to the first element. It is also very efficient as it short-circuits. - The
new Set()method is the most concise and clever solution. By converting the array to aSet, you can check if the.sizeis1to confirm all elements were duplicates.
Both methods are excellent, and the choice between them is often a matter of coding style preference.