Open In App

How to check all values of an array are equal or not in JavaScript ?

To check whether all values of an array are equal or not in JavaScript, we have multiple approaches.

Below are the approaches used to check if all values of an array are equal or not in JavaScript:



Approach 1: Using Array.every() method

Example: This example uses an array.every() method to print the desired response. 






let arr = [1, 1, 1, 1];
const allEqual =
    arr => arr.every(v => v === arr[0]);
 
console.log(allEqual(arr));

Output
true

Approach 2: Using Array.reduce() method

Example: This example uses an array.reduce() method to print the false for the given array. 




let arr = ["GFG", "GFG", "GFG", "GFG"];
function allEqual(arr) {
    if (!arr.length) return true;
    return arr.reduce(function (a, b) {
           return (a === b) ? a : (!b);
           }) === arr[0];
}
console.log(allEqual(arr));

Output
true

Approach 3: Using Set

In this article, we will pass the array to the Set constructor, and using the size property we can access the length of the array. As we know set stores unique elements and if the size of the set is 1 then it denotes that all the elements in the array are equal.

Example: This example shows the use of set for checking the equality of all the element in the array.




let arr = [1, 1, 1, 1];
 function allEqual(arr) {
  const res = new Set(arr).size === 1;
  return res;
}
 
console.log(allEqual(arr));

Output
true

Approach 4: Using for…of loop

The for…of loop iterates over the iterable objects (like Array, Map, Set, arguments object, …,etc) and will check the element is same as the first element.

Example: This example shows the use of for-of loop for checking the equality of all the element in the given array.




const arr = [1, 1, 1, 1];
const arr1 = [1, 1, 2];
function allEqual(array) {
    let areEqual = true;
 
    for (const element of array) {
        if (element !== array[0]) {
            areEqual = false;
            break;
        }
    }
 
    return areEqual;
}
console.log(allEqual(arr));
console.log(allEqual(arr1));

Output
true
false

Approach 5: Using filter() Method

In this approach, we will filter all the elements which are equal and compare the length of the new array with the original array.

Example: This example shows the use of filter() methodfor checking the equality of all the element in the given array.




const arr = [1, 1, 1, 1];
const arr1 = [1, 1, 2];
function allEqual(array) {
    return (
        array.filter(element => {
            return element === array[0];
        }).length === array.length
    );
}
console.log(allEqual(arr));
console.log(allEqual(arr1));

Output
true
false

Article Tags :