Reach a working result in a few minutes: filter a list, group it, and total each group — a pattern you can reuse for any array of records.
Prerequisites
- Node.js 4.0.0 or later.
- A project with a
package.json, or a.jsfile you can run withnode.
Install Lodash
bash
npm install lodashFilter, group, and total
1
Create a sample dataset
Create orders.js and add a small array of records to work with.
js
var _ = require('lodash');
var orders = [
{ id: 1, customer: 'ada', status: 'shipped', total: 42.5 },
{ id: 2, customer: 'grace', status: 'pending', total: 17 },
{ id: 3, customer: 'ada', status: 'shipped', total: 8 },
{ id: 4, customer: 'linus', status: 'cancelled', total: 30 },
{ id: 5, customer: 'grace', status: 'shipped', total: 12.25 }
];2
Filter with a shorthand predicate
Pass a partial object to _.filter instead of writing a comparison function — lodash treats { status: 'shipped' } as shorthand for order => order.status === 'shipped'.
js
var shipped = _.filter(orders, { status: 'shipped' });3
Group the results
_.groupBy takes a property path and returns an object keyed by that property's values.
js
var byCustomer = _.groupBy(shipped, 'customer');4
Total each group
_.mapValues runs a function over each value of an object and returns a new object with the same keys. sumBy adds up a property across an array of objects.
js
var totals = _.mapValues(byCustomer, function (customerOrders) {
return _.sumBy(customerOrders, 'total');
});
console.log(totals);5
Run the script
bash
node orders.jsExpected result
js
{ ada: 50.5, grace: 12.25 }linus and the pending order do not appear: _.filter already removed every order that was not shipped.
If you see
{ ada: 50.5, grace: 12.25 }, Lodash is installed correctly and you've combined three methods into one working pipeline.Next steps
- Combine steps like these into a single readable pipeline with chain sequences.
- See more shorthand forms in Iteratee shorthands and common patterns.
- Browse the full API reference organized by category.