Group or Count an array of values by property.
It required minimum 2 arguments. One is data set, second one is the properties array.
const getCountByProperty = require('count-by-property');
let users = [
{
name: 'User 1',
age: 22,
gender: 'male'
},
{
name: 'User 2',
age: 20,
gender: 'female'
},
{
name: 'User 3',
age: 23,
gender: 'male'
},
{
name: 'User 4',
age: 22,
gender: 'female'
}
];
let property = ['age', 'gender'];
objProerty(users, property);
Output:
{
age: {
'20': 1,
'22': 2,
'23': 1
},
gender: { male: 2, female: 2 }
}
To get grouped data, we must pass the third argument as 'true'. By default it was false.
const getCountByProperty = require('count-by-property');
let users = [
{
name: 'User 1',
age: 22,
gender: 'male'
},
{
name: 'User 2',
age: 20,
gender: 'female'
},
{
name: 'User 3',
age: 23,
gender: 'male'
},
{
name: 'User 4',
age: 22,
gender: 'female'
}
];
let property = ['age'];
objProerty(users, property, true);
Output:
{
'20': [{ name: 'User 2', age: 20, gender: 'female' }],
'22': [
{ name: 'User 1', age: 22, gender: 'male' },
{ name: 'User 4', age: 22, gender: 'female' }
],
'23': [{ name: 'User 3', age: 23, gender: 'male' }]
}