I have two object arrays:
array1 = [
{ name: 'Kitty, Hello',
otherNames: [ '(1) One', '(2) Two' ]
},
{ name: 'Cat, Garfield',
otherNames: [ '(3) Three' ]
}
];
array2 = [
{ name: 'Kitty, Hello',
otherNames: [ '(2) Two', '(1) One' ]
},
{ name: 'Cat, Garfield',
otherNames: [ '(3) Three' ]
}
]
I am trying to use Chai to see if they are equal, despite otherNames
being in a different order in array1
and `array2 .
I have tried:
array1.to.be.eql(array2) //false
array1.to.have.deep.members(array2) //false
But it keeps returning false. Is this even possible? I have tried looking at similar questions, but I could only find questions where "name" and "otherNames" were in different order.
Well they are not equals since they have different values in the array. You can sort the array and check if they are equal then.
const getSortedAtKey = (array, key = 'otherNames') => {
return array.map(value => ({
...value,
[key]: value[key].sort()
}));
}
expect(getSortedAtKey(array1)).to.eql(getSortedAtKey(array2))
This function is nice since you can chain it for multiple properties (if you have for example otherNames
and otherAges
arrays that you want to verify you can call getSortedAtKey(getSortedAtKey(array1), 'otherAges')