Functional Javascript Programming and Data Processing With Underscore

Functional Javascript Programming and Data Processing With Underscore

At, many of us heavily use Underscore JS within our Javascript codebases. Underscore provides a number of great functions that implement very common Javascript programming tasks, but a lot of the docs aren’t super self explanatory. It can sometimes be difficult to figure out how to use the various functional programming concepts that Underscore implements in your day-to-day code.

Fortunately, an excellent example data set fell into my lap the other week!

One of my coworkers handed me a giant CSV file containing all of the states in the United States, and asked me to turn it into a JSON array. While I tackled this task with the bulk text editing tools built into my text editor of choice (shout out to Sublime Text 3), this struck me as a pretty nifty data set to do some simple bulk data processing on.

We’ve made this JSON file available on Bitbucket for the public, and I’ll be using it as the demo data set for all of these examples. Get the JSON from our Bitbucket, and place it within the folder you intend to run these examples from, in a file named cities.json.

If needed, get Underscore.js from npm. Just run npm install -g underscore.

Now spin up a node.js instance, and run

The rest of these examples assume these variables will be defined and unmodified.

Let’s go ahead and do a couple of simple operations.

Underscore also really encourages javascript code reuse by making small functions that only accomplish a single task. Take the following utility function:

Using just this one function we can do a number of things, such as counting the number of cities in each state:

Grouping the list of cities into an array of cities for each state:

Getting rid of all of the cities in the state of Virginia:

How about getting rid of cities in _any_ Virginia (looking at you, WV):