I have this array of objects which have a lot of duplicate entries. I can clean the array and get rid of the duplicate ones but the catch is I need to remove those which matches based on the property's first 3 words.
Suppose this is the array:
let arr = [
{
text: "Be good and you will be lonely. But there’s nothing wrong with being lonely.",
id: 1
},
{
text: "Coffee is a way of stealing time.",
id: 2
},
{
text: "Be good and you will be lonely. But there’s nothing wrong with being lonely.",
id: 3
}
];
I want to match the first 3 words of each of the texts and if it is a match then remove one of the matched objects from the old array and push the removed one to a new array.
So far I could remove the duplicate ones with this piece of code and I don't know what I should do next.
let texts = {};
arr = arr.filter(function(currentObject) {
if (currentObject.text in seenNames) {
return false;
} else {
seenNames[currentObject.text] = true;
return true;
}
});
It would be a big help if someone point me to the right direction.
UPDATE:
I started the whole thing again with a different approach than before. As @Andreas and @freedomn-m said, I split the items based on the first 3 words and then tried to filter the original array by matching the split items. But right now I'm getting all the values back without any filtration.
let arr = [{
"text": "Be good and you will be lonely. But there’s nothing wrong with being lonely.",
"id": 1
},
{
"text": "Coffee is a way of stealing time.",
"id": 2
},
{
"text": "Be good and you will be lonely. But there’s nothing wrong with being lonely.",
"id": 3
}
];
let removedItems = [];
let filtered = arr.filter((item, index) => {
let splitItem = item["text"].split(" ").slice(0, 3).join(" ").toLowerCase();
if (item["text"].toLowerCase().startsWith(splitItem, index + 1)) {
return item;
} else {
removedItems.push(item);
}
});
console.log(filtered);
console.log(removedItems);