I have an array filled with objects. My goal is to identify and return the objects with unique IDs, avoiding any duplicates.
For example:
let arr1 = [
{id: 1, name: 'A'},
{id: 3, name: 'C'},
{id: 1, name: 'A'},
{id: 2, name: 'B'},
{id: 2, name: 'B'}
]
The desired result:
let newArr = [
{id: 1, name: 'A'},
{id: 2, name: 'B'}
]
The actual result:
let arr1 = [
{id: 1, name: 'A'},
{id: 3, name: 'C'},
{id: 2, name: 'B'}
]
I attempted the following solution:
arr1.reduce((destArray, obj) => {
if (destArray.findIndex(i => i.id === obj.id) < 0) {
return destArray.concat(obj);
} else {
return destArray;
}
}, [])
While this successfully filters objects by matching IDs, it also includes objects with somewhat unique IDs, which is not the desired outcome.