I have an array that looks like this.
var arr = [{
"taxname": "MFM",
"member": [{
"id": 1334,
"name": "Mary G. King",
}, {
"id": 1324,
"name": "Bonnie A. Wilson",
}, {
"id": 1336,
"name": "Samantha B. Sellers",
}]
},
{
"taxname": "Test purpose",
"member": [{
"id": 1336,
"name": "Samantha B. Sellers",
}]
},
{
"taxname": "New_Test_MF",
"member": [{
"id": 1334,
"name": "Mary G. King",
}]
}
];
I have flattened this out so it is just an array of objects.
const result = arr.reduce((r, obj) => r.concat(obj.member), []);
Result:
[{
id: 1334,
name: "Mary G. King"
}, {
id: 1324,
name: "Bonnie A. Wilson"
}, {
id: 1336,
name: "Samantha B. Sellers"
}, {
id: 1336,
name: "Samantha B. Sellers"
}, {
id: 1334,
name: "Mary G. King"
}]
After that remove the duplicate with id from the result, I did.
const ids = result.map(o => o.id)
const filtered = result.filter(({id}, index) => !ids.includes(id, index + 1))
Log the result:
console.log(filtered);
[{
id: 1324,
name: "Bonnie A. Wilson"
}, {
id: 1336,
name: "Samantha B. Sellers"
}, {
id: 1334,
name: "Mary G. King"
}]
I have got the result I wanted. But what is the best way of flattening, the array of objects and returning the unique array instead of using the multiple queries?