0

I have an array like this:

items ['A', 'A', 'B', 'C', 'C', 'C']

I want to know how to get results like this:

A = 2 item (s);
B = 1 item (s);
C = 3 item (s);

does anyone have an idea?

2 Answers2

1

Same answer as @Hakan Akin, different syntax

const count = ['A', 'A', 'B', 'C', 'C', 'C']
  .reduce((tmp, x) => ({
    ...tmp,
    
    [x]: (tmp[x] || 0) + 1,
  }), {});

console.log(count);
Orelsanpls
  • 22,456
  • 6
  • 42
  • 69
0

You can do it like that

items.reduce((prev, curr) => (prev[curr] = ++prev[curr] || 1, prev), {})

And this returns

Object {A: 2, B: 1, C: 3}
Hakan Akın
  • 1
  • 1
  • 3