I have an array of objects.
const arr = [
{ title: \"sky\", artist: \"Jon\", id: 1 },
{ title: \"rain\", artist: \"Paul\", id: 2 },
{ title: \"sky\", artis
You can group the items by id
, and then use _.flatMap()
to convert back a single array. In the _.flatMap()
callback return an empty array if the group has more than one item:
const fn = arr => _.flatMap(
_.groupBy(arr, 'id'), // group by the id
group => _.size(group) > 1 ? [] : group // check the size and return an empty array for groups with more than a single item
)
const arr1 = [{"title":"sky","artist":"Jon","id":1},{"title":"rain","artist":"Paul","id":2},{"title":"sky","artist":"Jon","id":1}]
const arr2 = [{"title":"sky","artist":"Jon","id":1},{"title":"rain","artist":"Paul","id":2},{"title":"sky","artist":"Jon","id":1},{"title":"rain","artist":"Paul","id":2}]
console.log(fn(arr1))
console.log(fn(arr2))
Another example