0

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?

2
  • 1
    retail[curr.status]++ should be ++retail[curr.status] or retail[curr.status]+1 Commented Oct 3, 2022 at 17:12
  • For some reason both id's are receiving equal values, like both of them have delivered: 9, sold: 2, in_delivery: 1. It should be different Commented Oct 3, 2022 at 17:56

1 Answer 1

1

You have two errors:

  1. You are using the postfix operator to increment count retail[curr.status]++, instead, use the prefix operator ++retail[curr.status] or simply (retail[curr.status] + 1).

  2. You are updating all the items, in an account, only the matching item should be updated.

Try this:

const userBuyers: any[] = buyers.reduce((acc: any[], curr) => {
    if (acc.filter((item) => item.id == curr.userBuyer).length == 0) {
      acc.push({ id: curr.userBuyer, [curr.status]: 1 });
      return acc;
    } else {
      acc = acc.map((retail) => {
        if (retail.id  === curr.userBuyer) {
          const isKey = retail[curr.status] ? true : false;
          return { ...retail, [curr.status]: isKey ? retail[curr.status] + 1 : 1 };
        }
        return retail;
      });
      return acc;
    }
  }, []);
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, it took me a bit to realize i was updating everything hahaha. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.