I have an array of objects.
const arr = [
{ title: "sky", artist: "Jon", id: 1 },
{ title: "rain", artist: "Paul", id: 2 },
{ title: "sky", artist: "Jon", id: 1 }
];
I would like to remove all duplicates from the array based on id. The final result should be
[{ title: "rain", artist: "Paul", id: 2 }]
If the array is
const arr = [
{ title: "sky", artist: "Jon", id: 1 },
{ title: "rain", artist: "Paul", id: 2 },
{ title: "sky", artist: "Jon", id: 1 },
{ title: "rain", artist: "Paul", id: 2 },
];
The result should be an [].
This is what I tried:
const arr = [{
title: "sky",
artist: "Jon",
id: 1
},
{
title: "rain",
artist: "Paul",
id: 2
},
{
title: "sky",
artist: "Jon",
id: 1
}
];
const uniqueScenarios = Array.from(new Set(arr.map(a => a.id)))
.map(id => {
return arr.find(a => a.id === id)
})
console.log(uniqueScenarios)
const arr1 = [{
title: "sky",
artist: "Jon",
id: 1
},
{
title: "rain",
artist: "Paul",
id: 2
},
{
title: "sky",
artist: "Jon",
id: 1
},
{
title: "rain",
artist: "Paul",
id: 2
}
];
const uniqueScenarios1 = Array.from(new Set(arr1.map(a => a.id)))
.map(id => {
return arr1.find(a => a.id === id)
})
console.log(uniqueScenarios1)
Please advice. I am open to lodash solutions as well. This is the final solution I am expecting. I am able to add Stackblitz link