I have an array with strings that I want to count:
const myArr = ["a, b, c", "a", "b", "a, b", "b", "a", "a", "a, b, c, d"]
I want to get a count for how many a
, b
, c
, and d
in myArr
.
Seeing answers from this post, I could use array methods, map()
, split()
, flat()
then reduce()
:
const res = myArr.map((x) => x.split(", ")).flat().reduce((acc, x) => {
return acc[x] ? ++acc[x] : (acc[x] = 1), acc;
}, {});
console.log(res)
// { a: 6, b: 5, c: 2, d: 1 }
Although the above code gives the desired output, I want to do everything within one run of reduce()
. Is it possible?
I've tried something out, but still don't know how I could complete it:
const res2 = myArr.reduce((acc, x) => {
acc.push(x.split(", "));
return acc.flat();
}, []);
console.log(res2)
// [ 'a', 'b', 'c', 'a', 'b', 'a', 'b', 'b', 'a', 'a', 'a', 'b', 'c', 'd' ]
// ^^^^^^^^^^ obviously not what I want!