Reputation: 11
var censusMembers = Object.freeze([
{
id: 1,
name: 'Bob'
}, {
id: 2,
name: 'Sue'
}, {
id: 3,
name: 'Mary',
household_id: 2
}, {
id: 4,
name: 'Elizabeth',
household_id: 6
}, {
id: 5,
name: 'Tom'
}, {
id: 6,
name: 'Jill'
}, {
id: 7,
name: 'John',
household_id: 6
}
]);
This is my array I want to count the number of elements which has household id using ramda function ? how can i do that ?
Upvotes: 1
Views: 271
Reputation: 193037
You can also use R.countBy
to count all items that have/don't have household_id
using R.has()
, and than get the count for true
using R.prop()
:
const { pipe, countBy, has, prop } = R;
const censusMembers = Object.freeze([{"id":1,"name":"Bob"},{"id":2,"name":"Sue"},{"id":3,"name":"Mary","household_id":2},{"id":4,"name":"Elizabeth","household_id":6},{"id":5,"name":"Tom"},{"id":6,"name":"Jill"},{"id":7,"name":"John","household_id":6}]);
const countHouseholders = pipe(
countBy(has('household_id')),
prop('true'),
);
const result = countHouseholders(censusMembers);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>
Upvotes: 3
Reputation: 33736
Don't use the function filter
to count stuff because you're creating an array only to get the length.
You can use the function R.reduce
and within the handler, check for the key household_id
var censusMembers = Object.freeze([{id: 1,name: 'Bob'}, {id: 2,name: 'Sue'}, {id: 3,name: 'Mary',household_id: 2}, {id: 4,name: 'Elizabeth',household_id: 6}, {id: 5,name: 'Tom'}, {id: 6,name: 'Jill'}, {id: 7,name: 'John',household_id: 6}]);
// With household_id
// (true is coerced to 1) = 1
console.log("With:", R.reduce((a, c) => ('household_id' in c) + a, 0, censusMembers));
// Without household_id
// !(false is coerced to 0) = 1
console.log("Without:", R.reduce((a, c) => !('household_id' in c) + a, 0, censusMembers));
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>
Upvotes: 0
Reputation: 50807
has
looks to be what you're missing:
var censusMembers = Object.freeze([
{id: 1, name: 'Bob'},
{id: 2, name: 'Sue' },
{id: 3, name: 'Mary', household_id: 2 },
{id: 4, name: 'Elizabeth', household_id: 6},
{id: 5, name: 'Tom'},
{id: 6, name: 'Jill'},
{id: 7, name: 'John', household_id: 6}
]);
const countHouseholders = R.pipe(R.filter(R.has('household_id')), R.length)
console.log(countHouseholders(censusMembers))
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>
Upvotes: 0