Category Archives: Underscore.js

Underscore.js: Introducing _.chain(…)

PROBLEM

Let’s assume we have the following JSON data:-

[
    {
        "date": "2015-07-30",
        "calendarAppointmentPtoJsonBeans": [
            {
                "basicEmployeeJsonBean": {
                    "id": 1,
                    "name": "Vrabel"
            	}
            }
        ]
    },
    {
        "date": "2015-07-31",
        "calendarAppointmentPtoJsonBeans": [
            {
                "basicEmployeeJsonBean": {
                    "id": 2,
                    "name": "Cray"
            	}
            },
            {
                "basicEmployeeJsonBean": {
                    "id": 1,
                    "name": "Vrabel"
            	}
            },
            {
                "basicEmployeeJsonBean": {
                    "id": 3,
                    "name": "Haeflinger"
            	}
            }
        ]
    }
]

What we want to do is to get all unique employees and ordered them by their names so that we get the following data:-

[
    {
        "id": 2,
        "name": "Cray"
    },
    {
        "id": 3,
        "name": "Haeflinger"
    },
    {
        "id": 1,
        "name": "Vrabel"
    }
]

SOLUTION 1: Less Elegant

Underscore.js provides various functions that allow us to pull this off.

var employees = _.sortBy( _.unique( _.pluck( _.flatten(
                _.pluck( jsonData, 'calendarAppointmentPtoJsonBeans' ) ),
                        'basicEmployeeJsonBean' ), function ( employee ) {
                    return employee.id;
                } ), function ( employee ) {
                    return employee.name;
                } );

While doable, the code is virtually not readable.

If you hate your peers and life, this is what you would write.

SOLUTION 2: More Elegant

The good news is Underscore.js also provides _.chain(..) that allows us to do the same thing through method chaining:-

var employees = _.chain( jsonData )
                .pluck( 'calendarAppointmentPtoJsonBeans' )
                .flatten()
                .pluck( 'basicEmployeeJsonBean' )
                .unique( function ( employee ) {
                    return employee.id;
                } )
                .sortBy( function ( employee ) {
                    return employee.name;
                } )
                .value();
Advertisements