Skip to content

Instantly share code, notes, and snippets.

@abhinavnigam2207
Last active September 6, 2017 06:05
Show Gist options
  • Save abhinavnigam2207/f7e8d3741daee34793d07ea16392aeeb to your computer and use it in GitHub Desktop.
Save abhinavnigam2207/f7e8d3741daee34793d07ea16392aeeb to your computer and use it in GitHub Desktop.
Check duplicates in an array by property and mark duplicates with a boolean flag.
const myArray = [
{id: 1, name: 'Abhinav', email: 'abhinav@gmail.com'},
{id: 2, name: 'Aviral', email: 'aviral@gmail.com'},
{id: 3, name: 'Jitendra', email: 'jitendra@gmail.com'},
{id: 4, name: 'Rajesh', email: 'rajesh@gmail.com'},
{id: 5, name: 'Abhinav', email: 'abhinav.nigam@gmail.com'},
{id: 6, name: 'Akash', email: 'akash@gmail.com'},
];
let arrayCopy = JSON.parse(JSON.stringify(myArray));
function checkDuplicates(propertyName, inputArray) {
let duplicateFound = false,
testObject = {};
inputArray.map(function(item) {
var itemPropertyName = item[propertyName];
if (itemPropertyName in testObject) {
testObject[itemPropertyName].duplicate = true;
item.duplicate = true;
duplicateFound = true;
}
else {
testObject[itemPropertyName] = item;
delete item.duplicate;
}
});
return duplicateFound;
}
console.log('The Array before processing: ', myArray);
console.log('Duplicates found in the array: '+ checkDuplicates('name', arrayCopy));
console.log('The Array after processing: ', arrayCopy );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment