I recently had a problem whereby I wanted to filter objects in an array by comparing the values of nested properties of each object to see if there were duplicates.
I have tried to explain as clearly as possible the scenario below and the solution I came up with. I wondering if it's possible to improve this solution and if so, how?
Example:
let articles = [{dateAdded: "31-5-1989", readId: 123, article: { id: 1}}, {dateAdded: "31-5-1989", readId: 124, article: { id: 2}}, {dateAdded: "31-5-1989", readId: 125, article: { id: 1}}]
In this array, you can see each object has a readId
and an articleId
. The first and last objects in the array have a different readId
but a matching articleId
. We want to return every object in this array unless we have already returned an object with the same articleId
.
Here is my solution:
const removeDuplicatesbyArticleId = articles => {
let articleIdsArray = [];
let finalArray = [];
articleResponse.reading.map(element => {
if (!articleIdsArray.includes(element.article.id)) {
articleIdsArray.push(element.article.id);
finalArray.push(element);
}
});
let filteredArticleResponse = articles;
filteredArticleResponse.reading = finalArray;
return filteredArticleResponse;
};
All I'm doing here is looping through the array, checking if the articleId
exists in the articleIdsArray
and if not, pushing this onto finalArray
and then repeating before returning finalArray at the end of the loop.
This solution feels a little crude, I'd be really grateful if anyone could suggest an alternative(s) solution(s) that is easier to read, better for performance, or both!
I apologise if this is a repeat, from much searching I couldn't find a question and answer that matched my specific case.