Actually, in the Lodash documentation, they give two pretty good examples for comparing and return fresh arrays for both differences and similarities (respectively in the examples below):
import { differenceWith, intersectionWith, isEqual } from 'lodash'
differenceWith(
[{ a: 1 }, { b: 1 }],
[{ a: 1 }, { b: 1 }, { c: 1 }],
isEqual
) // []... 💀the bigger array needs to go first!
differenceWith(
[{ a: 1 }, { b: 1 }, { c: 1 }],
[{ a: 1 }, { b: 1 }],
isEqual,
) // [{ c: 1 }] 🎉
intersectionWith(
[{ a: 1 }, { b: 1 }],
[{ a: 1 }, { b: 1 }, { c: 1 }],
isEqual,
) // [{ a: 1 }, { b: 1 }] 🎉this one doesn't care about which is bigger
If you won't always know which array will be bigger, you can write a helper function for it like so:
const biggerFirst = (arr1, arr2) => {
return arr1.length > arr2.length ? [arr1, arr2] : [arr2, arr1]
}
const [big, small] = biggerFirst(
[{ a: 1 }, { b: 1 }],
[{ a: 1 }, { b: 1 }, { c: 1 }],
)
differenceWith(big, small, isEqual) // 🎉even though we have no idea which is bigger when they are fed to biggerFirst()
From what I can tell, these match deeply as well so that's pretty nice.
I know relying on libraries for everything shouldn't be applauded, but this is the most concise/clean solution I've found to a really common problem. Hope it helps someone!
([] == []) == false.