Created
August 19, 2020 19:19
-
-
Save atembamanu/80e01b8e7a0706ac7c3131193828382b to your computer and use it in GitHub Desktop.
Duplicates in JS Array
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 data = [ | |
{ name: "Dev User", department: "ICT", taskPercentCompleted: 100 }, | |
{ name: "John Doe", department: "Finance", taskPercentCompleted: 100 }, | |
{ name: "Jane Doe", department: "Human Resource", taskPercentCompleted: 10 }, | |
{ name: "Jane Doe", department: "Human Resource", taskPercentCompleted: 100 }, | |
{ name: "Dev User", department: "ICT", taskPercentCompleted: 90 }, | |
{ name: "John Doe", department: "ICT", taskPercentCompleted: 100 }, | |
{ name: "John Doe", department: "ICT", taskPercentCompleted: 100 }, | |
]; | |
function countDuplicates(originalArray) { | |
var compressedArrayData = []; | |
const arrayCopy = originalArray.slice(0); | |
for (var i = 0; i < originalArray.length; i++) { | |
var counter = 0; | |
var avg = 0; | |
for (var j = 0; j < arrayCopy.length; j++) { | |
if (originalArray[i]["name"] === arrayCopy[j]["name"]) { | |
avg += arrayCopy[j]["taskPercentCompleted"]; | |
counter++; | |
} | |
} | |
if (counter > 0) { | |
var revisedFormat = new Object(); | |
revisedFormat.name = originalArray[i]["name"]; | |
revisedFormat.department = originalArray[i]["department"]; | |
revisedFormat.taskPercentCompleted = | |
originalArray[i]["taskPercentCompleted"]; | |
revisedFormat.avg = avg / counter; | |
revisedFormat.count = counter; | |
compressedArrayData.push(revisedFormat); | |
} | |
} | |
return compressedArrayData; | |
} | |
const validatedValues = countDuplicates(data); | |
console.log(data); | |
console.log(validatedValues); | |
//Get unique pairs | |
//Here i have used name to filter | |
let uniqueAssignment = validatedValues.filter( | |
(uniqueAssignment, index, self) => | |
index === | |
self.findIndex( | |
(t) => | |
t.name === uniqueAssignment.name && t.name === uniqueAssignment.name | |
) | |
); | |
console.log(uniqueAssignment); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment