Last active
October 18, 2019 20:14
-
-
Save rootedsoftware/c593442befd835e0bcab885fae320a6f to your computer and use it in GitHub Desktop.
Sort an Array by property, then find the duplicates by that property
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const users = [ | |
{ | |
firstName: 'Sarah', | |
lastName: 'Zulu', | |
email: '[email protected]', | |
}, | |
{ | |
firstName: 'Josh', | |
lastName: 'Able', | |
email: '[email protected]', | |
}, | |
{ | |
firstName: 'Bob', | |
lastName: 'Somebody', | |
email: '[email protected]', | |
}, | |
]; | |
// 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