groupby-array
v1.0.0
Published
Groups an array by the specified property
Downloads
6
Maintainers
Readme
groupby-array
Groups an array by the specified property.
Installation
yarn add groupby-array
or
npm install --save groupby-array
Usage
Basic usage
import { groupBy } from 'groupby-array';
const users = [
{ name: 'John', age: 30, isAdmin: true },
{ name: 'Jane', age: 25, isAdmin: true },
{ name: 'Jim', age: 30, isAdmin: false }
];
const result = groupBy(users, u => u.age);
// result
{
30: [
{ name: 'John', age: 30, isAdmin: true },
{ name: 'Jim', age: 30, isAdmin: false }
],
25: [
{ name: 'Jane', age: 25, isAdmin: true }
]
};
Group by multiple properties
const users = [
{ firstName: 'John', lastName: 'Doe', age: 30 },
{ firstName: 'Jane', lastName: 'Doe', age: 25 },
{ firstName: 'James', lastName: 'Bond', age: 30 }
];
const result = groupBy(users, u => `${u.firstName} ${u.lastName}`);
// result
{
'John Doe': [
{ firstName: 'John', lastName: 'Doe', age: 30 }
],
'Jane Doe': [
{ firstName: 'Jane', lastName: 'Doe', age: 25 }
],
'James Bond': [
{ firstName: 'James', lastName: 'Bond', age: 30 }
]
};
More examples can be found in the tests