group array and get count

前端 未结 6 482
执念已碎
执念已碎 2021-01-12 07:00

Say I have array like this:

[
   \"foo\",
   \"bar\",
   \"foo\"
   \"bar\",
   \"bar\",
   \"bar\",
   \"zoom\"
]

I want to group it so I

6条回答
  •  爱一瞬间的悲伤
    2021-01-12 07:41

    Yes you can reduce() your array to an object with the keys and the count, like this:

    const input = [
      "foo",
       "bar",
       "foo",
       "bar",
       "bar",
       "bar",
       "zoom"
    ];
    const result = input.reduce((total, value) => {
         total[value] = (total[value] || 0) + 1;
         return total;
    }, {});
    console.log(result);

    Hope it helps!

提交回复
热议问题