Trying to filter an array of objects by eliminating objects that have a specific property that exists already in another object (duplicate). The decision which object to remove should be based on another property.
Example: For an array of objects, that might look like this, the goal would be to filter all "user" duplicates and keep the one with the oldest "date" property.
const arr = [
{user: 'Alex', date: '1540801929945'},
{user: 'Bill', date: '1640801929946'},
{user: 'Carl', date: '1740801929947'},
{user: 'Alex', date: '1840801929948'},
]
Expected outcome:
filteredArr = [
{user: 'Alex', date: '1540801929945'},
{user: 'Bill', date: '1640801929946'},
{user: 'Carl', date: '1740801929947'},
]
I managed the basic filtering that works for keeping only unique objects.
const filteredArr = arr.reduce((unique, o) => {
if(!unique.some(obj => obj.user === o.user) {
unique.push(o);
}
return unique;
},[]);
Though I can't figure out, what to do so that in the case of a duplicate the "oldest" object stays and the latest get removed. Thanks so much for your help! Really appreciated.