In this final post on approaching functional programming with Javascript, we're taking our efforts from Part 1 and Part 2, where we're finalizing our JSON output into an object that meets our requirements:

  • filter out posts older than a month (say, 30 days).
  • group the posts by their tags (this might mean posts show up in two groups if they have more than one tag.)
  • sort each tag listing by published date, descending.

Now that we have an object which is filtered and grouped by tags, we need to do some sorting for each of the tag groups. Here's what our output currently looks like after running our app.js program:

  'destructuring': [
     { id: 2, title: 'ES6 Promises', tags: ['es6', 'promises'], /*...*/ },
     { id: 4, title: 'Basic Destructuring in ES6', tags: ['es6', 'destructuring'], /*...*/ },
  'es6': [ /*...*/ ],

We need to sort the records array for each tag group by their published date in descending (newest to oldest) order.

Check out the gist for the full source code (includes code for this post as well).

Sorting lists

Javascript makes sorting lists fairly easy with Array#sort(). Given no comparison function argument, .sort() will attempt to convert the elements to strings and sort in Unicode code point order. It also sorts the array in place. We want our sort to be pure, in that it won't mutate the array we're sorting; but return a newly sorted array.

Pure functions don't depend on or modify any state outside their own scope. They will always return the same result if given the same parameters.

Let's create a sort function that will take a list and a comparison function and return a new, sorted list.

function sort(list, fn) {  
  return [].concat(list).sort(fn);
var sortBy = rightCurry(sort);  // right curried version  

Here, we simply use Array#concat to create a new shallow copy of the array and then sort that one in place and return it. The comparison function is passed two objects at a time by Array#sort, a and b, and should do the following:

  1. if a < b, return -1 or less than 0 (sort will make index of a lower than b)
  2. if b < a, return 1 or greater than 0 (sort will make index of b lower than a)
  3. if a == b, return 0 (sort will not change the index of a or b)

Let's try that out with some lists:

var numbers = [5,1,3,2,4],  
    names = ['River','Zoë','Wash','Mal','Jayne','Book','Kaylee','Inara','Simon'];

function asc(a,b) {  
  return a < b ? -1 : (b < a) ? 1 : 0;

// [1, 2, 3, 4, 5]
// ["Book", "Inara", "Jayne", "Kaylee", "Mal", "River", "Simon", "Wash", "Zoë"]

* Note: names and numbers are unchanged

Creating generic comparators

The comparator function accepted by Array#sort() has a very specific interface which isn't very handy elsewhere. What would be better is if we could create generic, binary comparison functions that returned true or false and reuse them as comparators for Array#sort() somehow.

What we need is a higher-order function that can take our binary comparison which returns a boolean and give us a new function that can return -1, 0 or 1 to meet the interface we need.

Turns out, we can do this fairly easily. Let's call it comparator(), which takes a binary comparison function that returns true or false and returns a comparator function that holds to the API defined by Array#sort().

// Modify a simple binary comparison function to return the expected
// -1, 0, 1 return values used by sorting routines.
function comparator(fn) {  
    return function(a,b) {
        return fn(a,b) ? -1
            : fn(b,a) ? 1
            : 0;

Now let's see how we would use this with our previous example data.

var numbers = [5,1,3,2,4],  
    names = ['River','Zoë','Wash','Mal','Jayne','Book','Kaylee','Inara','Simon'];

// generic, binary comparison returning true|false
function lessThan(a,b) { return a < b; }

// create a comparator function
var asc = comparator(lessThan);

// [1, 2, 3, 4, 5]
// ["Book", "Inara", "Jayne", "Kaylee", "Mal", "River", "Simon", "Wash", "Zoë"]

This shows another benefit of using higher-order functions: we can consume functions and create new functions to accomplish more complex or specific tasks.

Higher-Order Functions are functions that take functions as arguments and/or return functions as values.

Comparing object properties

Our solutions so far have worked great for arrays that contain scalar values like numbers and strings. But we're working with arrays of objects. How do we use our generic comparison functions along with comparator() for sorting lists of objects by a given property?

Luckily, we've already solved this problem in the last post with our useWith() higher-order function.

useWith() allows us to modify the arguments sent to any function by passing them through another function. In this case, we want to ensure the two objects passed to our comparator go through another previous function we defined, getWith('published'), so that only the published property on each object is being compared.

Let's see how this actually works with some example code:

var kessel_times = [  
  { name: 'Slave 1', parsecs: 13.17 },
  { name: 'Falcon', parsecs: 11.5 },
  { name: 'Executor', parsecs: 18 }
var ascendingByParsecs = useWith(comparator(lessThan), getWith('parsecs'), getWith('parsecs'));

// [ 
//  { name: "Falcon", parsecs: 11.5 },
//  { name: "Slave 1", parsecs: 13.17 },
//  { name: "Executor", parsecs: 18 }
// ]

I've made a lot of special modifications myself...

Sorting our Groups by Published Date

Now, we have the tools we need to sort our output. We need to iterate over the groups in the output object (mapObject) and for each group, which is a list, sort the list by each object's published date (sortBy + comparator + useWith) in descending order, ie newest to oldest.

Let's give this a shot:

function greaterThan(a,b) {  
    return a > b;
var descending = comparator(greaterThan),  
    descendingByPublishDate = useWith(descending, getWith('published'), getWith('published'));

// Gets the group key and list of records for that group
function sortByPublishDate(group, recs) {  
    return sortBy(descendingByPublishDate)(recs);

var finished = mapObjectWith(sortByPublishDate)(finalgroups);  

This takes our output from our previous post, which was an object with property names matching the tag, each containing a list of records in non-sorted order; and gives us back the same style object, but with the list of records sorted by their published property.

  'es6': [
    { id: 7, displayDate: "2015-08-06", published: 1438876909394, ... }
    { id: 2, displayDate: "2015-07-26", published: 1437926509394, ... },
    { id: 9, displayDate: "2015-07-06", published: 1436205701255, ... }
  'functional programming': [
    { id: 10, displayDate: "2015-08-26", published: 1440604909394, ... },
    { id: 1, displayDate: "2015-07-25", published: 1437847125528, ... }

Outside of the helper functions we created in our functional library and within our app.js, here's the primary sequence of function calls to take our initial input and create our final output:

var filtered = filterWith(within30Days)(records);  
var bytags = pairWith(getWith('tags'))(filtered);  
var groupedtags = groupBy(getWith(1), bytags);  
var finalgroups = mapObjectWith(getPostRecords)(groupedtags);  
var finished = mapObjectWith(sortByPublishDate)(finalgroups);  

That's a fairly descriptive set of functions; and most of them are pure, higher-order functions that can be used to process other input or data as well. There were really only two functions specific to this application, which were getPostRecords() and sortByPublishDate() - everything else was done via our reusable set of binary comparison functions combined with our functional utility library we built.

Composing and Sequencing functions

One thing you'll notice in our application is that we continually do the following:

  1. Take an input list or object
  2. Pass it to a function to create an output
  3. Take that output and use it as an input (goto step #2)

This is a sequence or pipeline, where we have a series of functions that take an input, process it, and pass their output to the next function in the series. This is similar to the UNIX command line and its | (pipe) operator that hooks the output of the previous command into the input of the next command.

$ ps aux | grep "root"

We can do the same thing here, which is typically called composition in functional programming. For instance, taking a function g() and passing the output to function f() is similar to calling them as f(g()). In this case we invoke the function g() on our input and the output is passed to the function f() as its argument or input.

Here's a simple compose that works as above:

// Compose functions f() and g(), as f(g()) - f of g
function compose(f, g) {  
  return function() {
   var args = [];
    return f(g.apply(this, args));

This simple compose() function takes two functions as arguments and returns a function, that when executed, invokes the second function with that input and the first function with the result of that invocation.

function add1(val) {  
    return val + 1;

function square(val) {  
    return val * val;

// Composes two functions right to left
compose(square, add1)(4);  
// 25

However, in our current blog posts, we have multiple functions we are using to process our input. We'll need a more flexible compose() that can handle more than two functions as arguments to chain together.

// Compose: f(g(x)) for variable number of arguments (recursive)
function compose() {  
    var args = [],
        fn = args.shift(),
        gn = args.shift(),
        fog = gn ? function() { return fn(gn.apply(this, arguments)); } : fn;

    return args.length ? compose.apply(this, [fog].concat(args)) : fog;

Notice that compose chains its functions from right to left. This is the standard, as calling compose(f, g) is similar to saying f(g()), going right to left, inner to outer.

But with a pipeline, where we thinking of connecting functions together and giving an input at the left-hand side and getting our output on the right-hand side, it makes more sense to pass the functions in the order they would receive that input.

Let's create a pipeline() function that works just like compose() but with the argument order reversed to make sense in our context and read left to right.

var pipeline = flip(compose);  

Ha! Higher-order functions make this extremely easy. Now, let's take our previous calls in app.js and build a function that will chain each function's inputs and outputs the way we need to process them.

var mostRecentByTagOrderedByPublishDate = pipeline(  

var composed_finished = mostRecentByTagOrderedByPublishDate(records);  

If we compare the output of our composed function, you'll see it matches the output from before. You can also see now why we created right curried versions of each of our utility functions.

Having right curried versions, where the data to operate on is passed as the second, right-most and last argument, allowed us to build partially applied functions that we can pass to our compose() or pipeline() higher-order function to create more complex functions.


This has been a difficult series of posts to write (for me personally). We covered quite a few topics, from currying, both left and right, higher-order functions like map, filter and sort, and even function composition using compose() and pipeline(). The idea was to show how functional programming techniques can be used in a real world way to process data and build applications.

I hope that, at a high level, we've covered these topics well enough that you have a better understanding of functional programming in Javascript; but more importantly, that you might be encouraged to persue further reading on all these topics, to dig deeper and maybe use them in your own development.