Created
March 4, 2020 11:34
-
-
Save faisalhmohd/eaa4329f5174bb61ef79750c91817783 to your computer and use it in GitHub Desktop.
Remove Duplicates
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 testData = [ | |
{ | |
"id": 123, | |
"content": "Content", | |
"createTimestamp": 123213, | |
"answers": [ | |
{ | |
"id": 142, | |
"rating": 10, | |
"content": "Test answer" | |
}, | |
{ | |
"id": 242, | |
"rating": 2, | |
"content": "Test answer 2" | |
} | |
] | |
}, | |
{ | |
"id": 5, | |
"content": "Different content", | |
"createTimestamp": 123214, | |
"answers": [ | |
{ | |
"id": 342, | |
"rating": 15, | |
"content": "Test answer 3" | |
} | |
] | |
}, | |
{ | |
"id": 1024, | |
"content": "Content", | |
"createTimestamp": 54343, | |
"answers": [ | |
{ | |
"id": 442, | |
"rating": 9, | |
"content": "Test answer 4" | |
} | |
] | |
} | |
]; | |
function fetchMaxAnswersRating(answers) { | |
return answers.reduce((answer, maxScore) => { | |
if(answer && answer.rating > maxScore) { | |
return answer.rating | |
} | |
else return maxScore; | |
}, 0).rating; | |
} | |
function filterUniqueContents(contents) { | |
let results = [] | |
contents.map(content => { | |
const contentData = content.content; | |
const maxRating = fetchMaxAnswersRating(content.answers); | |
const similarContents = contents.filter(content => { | |
if (content.content === contentData) { | |
const tempMaxRating = fetchMaxAnswersRating(content.answers); | |
return maxRating > tempMaxRating; | |
} | |
}); | |
const isInResult = results.map(result => result.id === content.id).length; | |
if (similarContents.length) { | |
if (!isInResult) results.push(...similarContents); | |
} | |
else { | |
results.push(content); | |
} | |
}); | |
return results; | |
} | |
console.log(filterUniqueContents(testData)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment