count-by-property

1.0.5 • Public • Published

count by property

Group or Count an array of values by property.

Examples

Count

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 }
}

Group

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' }]
}

Readme

Keywords

none

Package Sidebar

Install

npm i count-by-property

Weekly Downloads

1

Version

1.0.5

License

ISC

Unpacked Size

4.08 kB

Total Files

4

Last publish

Collaborators

  • meumarsheik