Skip to content

Instantly share code, notes, and snippets.

@rootedsoftware
Last active October 18, 2019 20:14
Show Gist options
  • Save rootedsoftware/c593442befd835e0bcab885fae320a6f to your computer and use it in GitHub Desktop.
Save rootedsoftware/c593442befd835e0bcab885fae320a6f to your computer and use it in GitHub Desktop.
Sort an Array by property, then find the duplicates by that property
const users = [
{
firstName: 'Sarah',
lastName: 'Zulu',
email: 'sarah.zulu@test.com',
},
{
firstName: 'Josh',
lastName: 'Able',
email: 'sarah.zulu@test.com',
},
{
firstName: 'Bob',
lastName: 'Somebody',
email: 'bob.somebody@test.com',
},
];
// this is the property name we will use when checking for duplicates
const duplicateProperty = 'email';
// Sort by email so we can use the loop below
users.sort((a, b) => {
if(a[duplicateProperty] < b[duplicateProperty]) { return -1; }
if(a[duplicateProperty] > b[duplicateProperty]) { return 1; }
return 0;
});
var results = [];
// loop through and check the array item before the current one
// since the items are ordered by email in the sort function above
// we should find duplicates
// then we'll push those into the results array
for (var i = 0; i < users.length - 1; i++) {
if (users[i + 1][duplicateProperty] == users[i][duplicateProperty]) {
// Push this object
results.push(users[i]);
// Push the matching one so we can see both duplicates
results.push(users[i + 1]);
}
}
console.log(results);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment