How to count occurrences of a path in an array of objects with ramda.js?


How to count occurrences of a path in an array of objects with ramda.js?



I'm trying to use ramda.js to count occurrences of a key-value pair inside an array of objects, such as:


ramda.js


var array = [
{a: {b: 'a'}},
{a: {b: 'a'}},
{a: {b: 'X'}},
{a: 'a'}
]



If I wanted to count the number of times {a: {b: 'a'}} occurs inside of array in ramda.js, what would I do?


{a: {b: 'a'}}


array


ramda.js





Think in terms of these steps: [1] R.pathEq to check whether an array element matches [2] R.map to check every element of the array, converting it to true or false [3] Number can be used as a function to convert from true to 1 and false to 0 [4] R.sum to tally up all the 1s in the array Let me know if you need more assistance than the above and I can provide a complete solution.
– Scott Christopher
Jul 2 at 9:24



R.pathEq


R.map


true


false


Number


true


1


false


0


R.sum


1




1 Answer
1



You may hate it, pointfree function.


R.compose(R.length, R.filter(R.compose( R.equals('a'), R.path(['a', 'b']))))(array)



UPDATE Just learned from comment of Scott Christopher.



R.compose(R.equals(val), R.Path(p1, p2)) == R.pathEq([p1, p2], val)



function can be shorten to


R.compose(R.length, R.filter(R.pathEq(['a', 'b'], 'a')))(array)





Thank you, I think it's a good way as it's very concise :-) jsfiddle.net/8s9ae61L
– Gallaxhar
Jul 2 at 9:50







By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

api-platform.com Unable to generate an IRI for the item of type

How to set up datasource with Spring for HikariCP?

Display dokan vendor name on Woocommerce single product pages