I am not sure what your goal here is. You might be asking the question wrong. I think what you might be looking at is to remove duplicates from an array based on flags documentTypeId and flag with another condition that if there are duplicates you want to prefer the document which has flag=true.
You could try something like arranging all documentTypeIds in an array and sort them with boolean as first element and pick all documentTypeIds first element after the sort. Like below
const filterFn = (arr) => Object.values(
arr.reduce((acc, cur) => ({
...acc,
[cur.documentTypeId]: [...acc[cur.documentTypeId] || [], cur]
}), {}))
.map(i => i.sort(({flag: a}, {flag: b}) => Number(b) - Number(a))[0]);
const test1 = [{
"id": 100,
"documentTypeId": 3,
"docName": "test",
"flag": false
}, {
"id": 31184688089,
"documentTypeId": 1,
"docName": "test2",
"flag": true
},
{
"documentTypeId": 3,
"docName": "test3",
"flag": true,
"active": true
}
]
const test2 = [{
"docName": "test1",
"active": true,
"documentTypeId": 3,
"flag": false
},
{
"docName": "test2",
"active": true,
"documentTypeId": 1,
"flag": false
},
{
"docName": "test3",
"documentTypeId": 5,
"id": 5,
"flag": false
},
{
"docName": "test4",
"active": true,
"documentTypeId": 16,
"flag": false
},
{
"docName": "test5",
"documentTypeId": 16,
"id": 102,
"flag": true
}
]
const filterFn = (arr) => Object.values(
arr.reduce((acc, cur) => ({
...acc,
[cur.documentTypeId]: [...acc[cur.documentTypeId] || [], cur]
}), {}))
.map(i => i.sort(({flag: a}, {flag: b}) => Number(b) - Number(a))[0]);
console.log(filterFn(test1));
console.log(filterFn(test2));