I am using React framework and passing a prop to a component that maintains a state. The prop and state are arrays of objects, and I want to verify whether or not there is any change between the two at some point in my code.
somethingHasChanged = () => {
return !isEqual(this.props.array1.sort(), this.state.array1.sort());
};
Where the objects in the array are defined like so:
array1: PropTypes.arrayOf(
PropTypes.shape({
id: PropTypes.string,
name: PropTypes.string,
label: PropTypes.string,
}),
),
The id can be repeated in several objects in the array, so it does not uniquely identify one object. Name and label are optional keys in the json object but it doesn't have to be specified.
Right now I sort both arrays and then check if they are equal, but I'm seeing some weird behavior. Sometimes when I expect both arrays to be equal, they are different because the content is the same but the ordering is not the same even though I call sort() on both. Is there a better, easier/more flexible approach rather than doing a deep comparison?
isEqual. The sort is not working as you expect it to behave, because the sort function does not understand which object is bigger or smaller.sort()then. It makes sense to me if one array has something different than the other, but in this case (at least from what I know), both arrays are the same