object has some really useful methods for working with
collections of data, like
These methods are often good enough, but
can make working with collections even sweeter.
Let's take a contrived example. Say you have an array of user objects, and you want to get the email addresses of all active users, sorted by the date they signed up. Let's also say that some users don't have email addresses, so you want to filter those out.
const chain =compactvalue
I find that second version is easier to write, and easier to read.
value() call at the end. Remember to always call that last.
lodash's convenience methods attached to its prototype. A few of my favorites:
firstreturns the first element in the collection
lastreturns the last
flattenturns arrays of arrays into one flat array
compactremoves falsy values
picklets you specify which properties you want from each object
omitlets you specify which properties you don't want from each object
orderBysorts by a property name and optional direction
samplereturns a random element
shufflerandomly arranges the values
There are lots of them. See lodash.com/docs.
For many years I was a rubyist. That is, a reader and writer of the Ruby programming
language. I loved the expressiveness and flexibility of Ruby, and in particular
I loved its Enumerable
module which, like
chain, provides a bunch of really useful methods for
working with collections.
chain method makes me miss Ruby just a little less. Combined
is really starting to grow up.
Nota Bene means "observe carefully" or "take note". I just learned that.
If you're writing code targeting browsers (as opposed to Node) you might want to
think twice about using
chain, because it will make your bundle bigger.
lodash publishes standalone packages to npm like
lodash.uniq, but not
chain because it requires all of lodash.
There are a number of ways to roll your own lodash build, though. See the lodash functional programming guide for details.