Search code examples
javascriptarraysobjectcomparisonequality

For an array of JSON conform object literals, how does one compare the equality of such items?


How to check if array contains different values with React.js and typescript?

Example:

[{
  name: 'John',
  value: 1,
}, {
  name: 'John',
  value: 1,
}, {
  name: 'Carla',
  value: 15,
}]

I want to return false if all objects in array are same, and true if there is at least one different object.


Solution

  • You can't use a direct equality comparison since objects will never return equal.

    Ie {} != {}, and {name: 'John', value: 1} != {name: 'John', value: 1}.

    So firstly you have to decide what you're going to define as 'equal' for these objects.

    Let's say for the sake of this that you use just the name field as the test for equality. So if two objects in the array have the same name field, then you'll call them equal. Then you'd define the function:

    type NameValue = {name: string, value: string}
    
    const areEqual = (obj1: NameValue, obj2: NameValue): boolean => obj1.name === obj2.name
    

    Of course you can change this function to reflect whatever you define as 'equal'. There are npm packages to help you with deep equality checks too, or you can JSON.stringify both and check that equality

    Then you can use Array.some(). Array.some() will return true if any element in the array passes a test. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some

    Testing if any element is not equal to the first should be sufficient.

    const areNotAllEqual = yourArray.some((currentElement) => {
      return !areEqual(currentElement, yourArray[0])
    })