0

Is it possible to have the number of occurrences of each value in an array?

For example :

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

I want to display :

pineapple appears 1 time, apples appears 2 times etc..

  • duplicate of https://stackoverflow.com/questions/12749200/how-to-count-array-elements-by-each-element-in-javascript – Parth Ghiya May 29 '17 at 12:41
  • 2
    Possible duplicate of [How to count array elements by each element in javascript](https://stackoverflow.com/questions/12749200/how-to-count-array-elements-by-each-element-in-javascript) – Parth Ghiya May 29 '17 at 12:41
  • 1
    This has nothing to do with Angular. It's plain old JavaScript. –  May 29 '17 at 12:46

1 Answers1

0

You can try the below code

const items = ["pineapple", "apples", "tomatoes", "water", "apples","tomatoes"];
items.reduce((counts, curr) => (counts[curr] = ++counts[curr] || 1, counts), {});
jpaugh
  • 6,634
  • 4
  • 38
  • 90
Rjoydip
  • 66
  • 3