1.0.0 • Published 9 years ago
nest-by v1.0.0
nest-by
Groups an array/object by property values or callback
Works like group-by or lodash.groupBy, but also:
- can nest recursively
- works with objects as well as arrays
Usage
nestBy(object or array, property, [...properties])
Arrays
list =
[ { name: 'Marge', gender: 'f' },
{ name: 'Homer', gender: 'm' },
{ name: 'Bart', gender: 'm' } ]
result = nestBy(list, 'gender')
// { f: [ { name: 'Marge', gender: 'f' } ],
// m: [ { name: 'Homer', gender: 'm' },
// { name: 'Bart', gender: 'm' } ] }
Objects
list =
{ marge: { name: 'Marge', gender: 'f' },
homer: { name: 'Homer', gender: 'm' },
bart: { name: 'Bart', gender: 'm' } }
var result = nestBy(list, 'gender')
// f:
// marge: { name: 'Marge', gender: 'f' }
// m:
// homer: { name: 'Homer', gender: 'm' }
// bart: { name: 'Bart', gender: 'm' }
Recursive
list =
[ { name: 'Marge', gender: 'f' },
{ name: 'Homer', gender: 'm' },
{ name: 'Bart', gender: 'm' } ]
result = nestBy(list, 'gender', 'name')
// f:
// 'Marge':
// [ { name: 'Marge', gender: 'f' } ]
// m:
// 'Homer':
// [ { name: 'Homer', gender: 'm' } ]
// 'Bart':
// [ { name: 'Bart', gender: 'm' } ]
Thanks
nest-by © 2015+, Rico Sta. Cruz. Released under the MIT License. Authored and maintained by Rico Sta. Cruz with help from contributors (list).
ricostacruz.com · GitHub @rstacruz · Twitter @rstacruz
1.0.0
9 years ago