数组中出现的次数

时间:2017-05-29 12:39:16

标签: javascript arrays find-occurrences

是否可以在数组中包含每个值的出现次数?

例如:

items = ["pineapple", "apples", "tomatoes", "water", "apples","tomatoes"];

我想要显示:

  菠萝出现1次,苹果出现2次等。

1 个答案:

答案 0 :(得分:0)

您可以尝试以下代码

const items = ["pineapple", "apples", "tomatoes", "water", "apples","tomatoes"];
items.reduce((counts, curr) => (counts[curr] = ++counts[curr] || 1, counts), {});