Reputation: 31
I have an array with duplicate values and I need to find out how many times each value occurs in the array using ramda.js.
This is my array: [2013, 2013, 2013, 2014, 2014, 2014, 2014, 2015, 2015, 2015, 2015, 2015, 2015, 2015, 2016, 2016, 2016, 2016, 2016, 2017, 2017, 2017]
This is what I want to get out of it: [3, 4, 7, 5, 3]
Here's an example of how it might work in pure JavaScript.
function count (arr) {
const counts = {}
arr.forEach((x) => { counts[x] = (counts[x] || 0) + 1 })
return Object.values(counts)
}
Upvotes: 3
Views: 2512
Reputation: 191976
Assuming that (like in your code) the duplicates don't have to be in sequence, you can get the same results with R.countBy()
and R.values()
:
const { pipe, countBy, identity, values } = R;
const arr = [2013, 2013, 2013, 2014, 2014, 2014, 2014, 2015, 2015, 2015, 2015, 2015, 2015, 2015, 2016, 2016, 2016, 2016, 2016, 2017, 2017, 2017]
const countDupes = pipe(
countBy(identity),
values
)
console.log(countDupes(arr));
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js"></script>
Upvotes: 6