Reputation: 460
I have an array of objects of which I am trying to remove the duplicate elements from.
BUT with a condition. I only want to remove the ones where title
=== title
If it does equal title
, then it should remove the object without the taggedPosts
property
End result would look like this
I've tried a lot of ways, but they all seem to only return the ones without the taggedPosts
property and remove the ones with that property which is not what I want. Particularly _.uniq(array)
from lodash.
Thanks for the help.
Upvotes: 1
Views: 111
Reputation: 2085
Here is the vanilla javascript way
for each object in the array, we are looking for another object with same title and taggedPosts, if yes, we filter out the current object.
data.filter((item, index) => !data.find((innerItem, innInd) => innerItem.title === item.title && innerItem.taggedPosts && index !== innInd))
Upvotes: 0
Reputation: 20885
I suggest you use the _.remove
function from lodash instead.
For each element, check if a dupe exists and remove that element if it does not have the taggedPosts
property.
const data = [
{title: '1', taggedPosts: []},
{title: '2', taggedPosts: []},
{title: '3', taggedPosts: []},
{title: '4', taggedPosts: []},
{title: '1'},
{title: '5'},
{title: '3'},
{title: '6'},
];
_.remove(data, e => {
// Search for a potential duplicate
const dupe = data.find(d => d.title === e.title && d !== e);
// Remove it if there is a duplicate and the current element does not have taggedPosts
return dupe && !e.taggedPosts;
});
console.log(data);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
Note: remove modifies the array in place.
Upvotes: 2