i have a array of object from there i need to filter duplicate item based on two key on return with extra key on it
let word = [
{
start: 1,
end: 4,
name: "alex",
},
{
start: 5,
end: 8,
name: "sam",
},
{
start: 1,
end: 4,
name: "alex",
},
{
start: 85,
end: 114,
name: "Abhishek",
},
{
start: 1,
end: 4,
name: "alex",
},
];
in above sample i want to filter out duplicate based on start and end key also need to add a key called haveDuplicate if same object have duplicate it need to be true
let filterd = [
{
start: 5,
end: 8,
name: "sam",
},
{
start: 85,
end: 114,
name: "Abhishek",
},
{
start: 1,
end: 4,
haveDuplicate: true,
name: "alex",
},
];
i tried lodash but i cannot able to add extra key below is what i tried
_.uniqBy(data, obj => obj.start && obj.end);
You can use Array.prototype.reduce() and check if the item exist with Array.prototype.find() for that like so:
let word = [
{
start: 1,
end: 4,
name: "alex",
},
{
start: 5,
end: 8,
name: "sam",
},
{
start: 1,
end: 4,
name: "alex",
},
{
start: 85,
end: 114,
name: "Abhishek",
},
{
start: 1,
end: 4,
name: "alex",
},
];
const filteredArr = word.reduce((acc, curr) => {
const obj = acc.find(item => item.start === curr.start && item.end === curr.end);
if(obj) {
if(!obj.haveDuplicate) {
obj.haveDuplicate = true;
}
return acc;
}
acc.push(curr);
return acc;
}, []);
console.log(filteredArr);
Here's an idea, use _.groupBy, and we can read number of items in group to determine if it has duplicate.
let word = [
{
start: 1,
end: 4,
name: "alex",
},
{
start: 5,
end: 8,
name: "sam",
},
{
start: 1,
end: 4,
name: "alex",
},
{
start: 85,
end: 114,
name: "Abhishek",
},
{
start: 1,
end: 4,
name: "alex",
},
];
const grouped = _.groupBy(word, o => `${o.start}-${o.end}`);
const result = _.map(grouped, occurrences => {
if (occurrences.length > 1) return { ...occurrences[0], haveDuplicate: true };
return occurrences[0];
})
console.log(result);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
You can combine reduce and Object.values
Object.values(word.reduce( (a,x) => { if(a[x.start+'-'+x.end]) x = {...x, haveDuplicate: true}; return a[x.start+'-'+x.end]=x,a} , {} ))