Search code examples
javascriptarraysreactjsobjectlodash

How to compare two big arrays of objects on identity


I have to compare two big arrays of objects in react componentwillreceiveprops. I have array of 261 countries. For example it begins from this.

 countries = [
     {id: 1, name: "Australia", code: "AU", isRemoved: false}
      ...
      261 objects
 ]

I must compare that the array that will be received in next props is absolute identical with my current countries array, that is all properties, length, property values, all things are equal. Please help me. I wrote something like this, but I know just !== not correct.

if (this.state.countriesInitial !== countries) {//TODO: compare arrays
      this.setState({
          countriesInitial: countries
      })
}

Any answers will be taken into acccount. Maybe lodash has some methods that will simplify the task, i dont know. Any answers will be considered. Thanks in advance.


Solution

  • Yes, lodash has a method that makes life easier - _.isEqual():

    var arr1 = [ /* Very long array */ ],
        arr2 = [ /* Also long array */ ];
    var equalArrays = _.isEqual(arr1, arr2);
    

    Alternatively, use JSON methods:

    var arr1 = [ /* Very long array */ ],
        arr2 = [ /* Also long array */ ];
    var equalArrays = JSON.stringify(arr1) == JSON.stringify(arr2);