Hammad Khalid
Hammad Khalid

Reputation: 548

Ramda, counting value frequency in array

I have the following simple array

['a', 'b', 'a', 'c', 'a', 'c', 'd', 'a']

How can Ramda help me in achieving the following

{a: 4, b: 1, c: 2, d: 1}

a:4 represents that value a exists 4 times in the main array

b:1 represents that value b exists 1 time in the main array

c:2 represents that value c exists 2 times in the main array

d:1 represents that value d exists 1 time in the main array

Upvotes: 0

Views: 334

Answers (1)

Ori Drori
Ori Drori

Reputation: 191976

Use R.countBy with R.identity as the function that generates the keys:

const data = ['a', 'b', 'a', 'c', 'a', 'c', 'd', 'a']

const result = R.countBy(R.identity, data)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>

Upvotes: 3

Related Questions