Last active
September 6, 2017 06:05
-
-
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.
This file contains 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 myArray = [ | |
{id: 1, name: 'Abhinav', email: '[email protected]'}, | |
{id: 2, name: 'Aviral', email: '[email protected]'}, | |
{id: 3, name: 'Jitendra', email: '[email protected]'}, | |
{id: 4, name: 'Rajesh', email: '[email protected]'}, | |
{id: 5, name: 'Abhinav', email: '[email protected]'}, | |
{id: 6, name: 'Akash', email: '[email protected]'}, | |
]; | |
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