Check If All JavaScript Object Values Are Equal

In this article, we will discuss how to check if all values within a JavaScript object are equal. To accomplish this, we will create an array of the object’s values using the Object.values() method. Subsequently, we will employ the every() method on our array to compare each value with the first element, determining if they are all equal.

Check If All JavaScript Object Values Are Equal

Let’s begin by creating an object and initializing it with some values. For our demonstration, we will use numeric values, but this approach can be applied to any data type.

const numbers = {

  one: 1,

  two: 2,

  three: 3,

  four: 4

};

Next, we will create an array with our object’s values using the `Object.values()` method –

const numberValues = Object.values(numbers);

Then, to check if all the values inside our `numberValues` array are equal, we will use the `every()` method to iterate over our array, and on each iteration, we will compare the element at the current index with the first element inside of our array. In case all our object values are equal, we should return `true`, otherwise if a value is found not equal to the first element, our loop exits automatically and returns `false`.

numberValues.every((value, _index, array) => {
  if (value === array[0]) {
    return true;
  }
  return false;
});

If we need to check the output of this statement, we can print it on the console –

console.log(
  numberValues.every((value, _index, array) => {
    if (value === array[0]) {
      return true;
    }
    return false;
  })
);
check if all JavaScript object values are equal

Executing the code, we can observe that the output on the console is false, indicating that our object values are not all equal.

For enhanced usability, let’s encapsulate our logic within a function that can be invoked on any object to check if its values are equal.

const areValuesEqual = (object) => {
  return Object.values(object).every((value, _index, array) => {
    if (value === array[0]) {
      return true;
    }
    return false;
  });
};

Now let’s modify our object and set all the values to the same value and try calling our function on the `numbers` object, then check what we have on the console.

const numbers = {
  num1: 1,
  num2: 1,
  num3: 1,
  num4: 1
};

console.log(areValuesEqual(numbers));
true is the output on the console

Upon executing the code, we can see that the output on the console is true, indicating that all values within the numbers object are equal to 1.

Conclusion

In conclusion, by utilizing the Object.values() method to create an array of object values and then applying the every() method to check for equality, we can easily determine if all values within a JavaScript object are equal. This approach provides a flexible solution that can be used with various objects and data types.

Leave a Reply