是否可以在数组中包含每个值的出现次数?
例如:
items = ["pineapple", "apples", "tomatoes", "water", "apples","tomatoes"];
我想要显示:
菠萝出现1次,苹果出现2次等。
答案 0 :(得分:0)
您可以尝试以下代码
const items = ["pineapple", "apples", "tomatoes", "water", "apples","tomatoes"];
items.reduce((counts, curr) => (counts[curr] = ++counts[curr] || 1, counts), {});