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 the order of otherNmaes for the first object in array1.
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.
CodePudding user response:
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')
CodePudding user response:
There is a package for that. https://www.npmjs.com/package/deep-equal-in-any-order
const deepEqualInAnyOrder = require('deep-equal-in-any-order');
const chai = require('chai');
chai.use(deepEqualInAnyOrder);
const { expect } = chai;
expect(array1).to.deep.equalInAnyOrder(array2);