How to group 2 arrays and push the matches to new array with status count, if status count repeats then increment the status
here compare array a’s id with array b assigned, if both are equal add a new key to a with count which contains the count of status.
I have tried with map but got the object seperately and was not able to seggrate it based on the id. please help
`const a = [
{
id: 1,
name: "Mark",
},
{
id: 2,
name: "John",
},
{
id: 3,
name: "Ruth",
}
]
let b = [
{
assigned: [1],
status: "C"
},
{
assigned: [1, 2],
status: "S"
},
{
assigned: [2],
status: "O"
},
{
assigned: [2, 3],
status: "C"
}
];
const result = [{
id: 1,
name: "Mark",
count: {
"C": 1,
"S": 1
},
},
{
id: 2,
name: "John",
count: {
"C": 1,
"S": 1,
"O": 1
},
},
{
user_id: 3,
name: "Ruth",
count: {
"C": 1
},
}
]`
` const resultArr = []
a.map(el => {
b.map(elm => {
if(elm.assigned.includes(el.id)){
resultArr.push({...el, [elm.status]: 1})
}
})
})`
>Solution :
You can use a combination of Array.map()
and Array.reduce()
to get the desired result.
For each element in the a
array, we call b.reduce() to produce the output object for each value in the a array. This essentially involves checking each assigned
array for the id of the element, and if it exists, incrementing the count for the relevant status.
const a = [ { id: 1, name: "Mark", }, { id: 2, name: "John", }, { id: 3, name: "Ruth", } ]
const b = [ { assigned: [1], status: "C" }, { assigned: [1, 2], status: "S" }, { assigned: [2], status: "O" }, { assigned: [2, 3], status: "C" } ];
const result = a.map(({ id, name }) => {
return b.reduce((acc, { assigned, status}) => {
if (assigned.includes(id)) {
acc.count[status] = (acc.count[status] || 0) + 1;
}
return acc;
}, { id, name, count: {} })
})
console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; }