I have an object that has the key ID and some status key. I wanna count how many times the same status repeats itself. My object will look like this
const items = { id: 2, status_a: 1, status_b: 1, status_c: 3 };
This is my code
curr.userBuyer is a number. curr.status is a string, for each equal status, i want to add 1 to it
const userBuyers: any[] = buyers.reduce((acc: any[], curr) => {
if (acc.filter((item) => item.id == curr.userBuyer).length == 0) {
//If the there's no item in acc, then it gets pushed into it
acc.push({ id: curr.userBuyer, [curr.status]: 1 });
return acc;
} else {
//If acc already have that item
acc = acc.map((retail) => {
//Check if that key already exists
const isKey = retail[curr.status] ? true : false;
//If the key exists, then it will add 1 to the existing value, else it will set it as 1
return { ...retail, [curr.status]: isKey ? retail[curr.status]++ : 1 };
});
return acc;
}
}, []);
This is what is returning
[
{
id: 713,
delivered: 1,
sold: 1,
in_delivery: 1,
},
{
id: 833,
delivered: 1,
sold: 1,
in_delivery: 1,
},
];
It's not adding 1 to the status that already exists.
What am i doing wrong?
retail[curr.status]++should be++retail[curr.status]orretail[curr.status]+1