I want to compare 2 array of objects with floating point property to see if they are equal, regardless of the order of elements. The array may contain duplicate elements. I already have a function to determine whether two objects are equal, however, I have no idea how to compare 2 arrays.
const arr1 = [
{
foo: "obj1",
bar: 0.1
},
{
foo: "obj2",
bar: 0.3
},
{
foo: "obj2",
bar: 0.3
}
];
const arr2 = [
{
foo: "obj2",
bar: 0.1 + 0.2
},
{
foo: "obj1",
bar: 0.1
},
{
foo: "obj2",
bar: 0.3
}
];
const compareObject = (o1, o2) => {
if (o1.foo !== o2.foo) {
return false;
}
const threshold = 0.00000001;
return Math.abs(o1.bar - o2.bar) < threshold;
};
const compareArr = (arr1, arr2) => {
// how to compare?
};
compareArr(arr1, arr2) // should return true
Clarify: The function should only return true if 2 arrays are exactly matched regardless of the order of elements, and there may be duplicate elements inside an array, i.e.
const arr1 = [obj1, obj1, obj2];
const arr2 = [obj1, obj2, obj2];
compareArr(arr1, arr2) // should return false