I want to create a new object, where the users should only appear once.
So if a person appears multiple times, which is given when given_name and family_name both match, all but one are removed.
Example:
[
{
given_name: 'Aha',
family_name: 'Yes',
email: 'Yes@gmail.com',
},
{
given_name: 'Testname',
family_name: 'Test',
email: 'Testname@gmail.com',
},
{
given_name: 'Hans',
family_name: 'Test',
email: 'Testname@gmail.com',
},
{
given_name: 'Aha',
family_name: 'Yes',
email: 'Yesassss@gmail.com',
}
]
So the above should result in this:
[
{
given_name: 'Aha',
family_name: 'Yes',
email: 'Yes@gmail.com',
},
{
given_name: 'Testname',
family_name: 'Test',
email: 'Testname@gmail.com',
},
{
given_name: 'Hans',
family_name: 'Test',
email: 'Testname@gmail.com',
}
]
You can do something like this, here we are using a map to get the unique values. For the keys in the map, we use a combination of given_name and family_name.
const users = [{given_name: "Aha", family_name: "Yes", email: "Yes@gmail.com"}, {given_name: "Testname", family_name: "Test", email: "Testname@gmail.com"}, {given_name: "Hans", family_name: "Test", email: "Testname@gmail.com"}, {given_name: "Aha", family_name: "Yes", email: "Yesassss@gmail.com"}];
const removeDuplicates = (data) => {
const userNameMap = {};
data.forEach((user) => {
const userName = `${user.given_name}|${user.family_name}`;
userNameMap[userName] = user;
});
return Object.values(userNameMap);
};
console.log(removeDuplicates(users));
Please use the below one liner code
let arr = arr.filter((item,index)=>arr.findIndex(item2=>(item.family_name == item2.family_name && item.given_name == item2.given_name))>=index)