Skip to main content

JavaScript: underscorejs with examples

In previous post I have mention about underscorejs library. And here is the another post to explain bit more about this library.

Some functions used in below example to improve readability 
function prop(name){
 return function(obj){
  return obj[name];

function compareProp(prop, contextProp){
 return function(obj){
  return obj[prop] === this[contextProp];

Find visible user and show it’s default view
Below is the list of JSON array with user object data. Now we want to show all visible user with it’s default view.
var ar = [{
 name: 'moe',
 age: 40,
 display: true,
 defaultView: 1,
 views: [ 
  { name: 'Admin', id: 1 }, 
    { name: 'Role1', id: 2 }, 
    { name: 'Role2', id: 3 } 
 name: 'larry',
 age: 50,
 display: false,
 defaultView: 1,
 views: [ 
  { name: 'Admin', id: 1 }, 
    { name: 'Role1', id: 2 }, 
    { name: 'Role2', id: 3 } 
 name: 'curly',
 age: 60,
 display: true,
 defaultView: 2,
 views: [ 
  { name: 'Admin', id: 1 }, 
    { name: 'Role1', id: 2 }, 
    { name: 'Role2', id: 3 } 

Output must be
["moe has default view of Admin", 
"curly has default view of Role1"]

Solution without underscorejs library
var data = [];
for(var i=0, il=ar.length; i<il; i++){
    var item = ar[i];
        var str = + " has default view of ";
        for(var j=0, jl=item.views.length; j<jl; j++){
            var view = item.views[j];
            if( === item.defaultView){
                str +=;

And after using underscorejs library
var userDefaultView = function(user){ 
 return + ' has default view of '+ _.find(user.views,compareProp('id','defaultView'),user).name;

by using filter and map
Above method will iterate twice on the list, first for filtering and then for transforming, so performance will not be so good. Here is the better way of achieving the same thing by using reduce method.
_.reduce(ar, function(memo, user){
    return memo;
}, []);
Parse array data based on it’s type
var data = [
 { value:"test string",  type:"string" },
 { value:"221132",   type:"int" },
 { value:"21112.21212",  type:"float" },
 { value:"2012-09-22T17:01Z", type:"date" },
 { value:"2012-09-22T17:01Z", type:"datetime" },
 { value:"test2 string",  type:"string" },
 { value:"True",   type:"boolean" },
 { value:"234.1214",  type:"int" },
 { value:"2000-09-22T04:20Z", type:"date" },
 { value:"False",   type:"boolean" }
and output must be
["test string",
"9/22/2012 17:01",
"test2 string",
some formatter functions
var formattor = function(){
 function stringFormattor(value)  { return value; }
 function intFormattor(value)  { return parseInt(value, 10); }
 function floatFormattor(value)  { return parseFloat(value, 10); }
 function dateFormattor(value)  { return Date.parse(value).toString("M/d/yyyy"); }
 function datetimeFormattor(value) { return Date.parse(value).toString("M/d/yyyy HH:mm"); }
 function booleanFormattor(value) { return value === "True"; }

 return {
  "string" : stringFormattor,
  "int"  : intFormattor,
  "float"  : floatFormattor,
  "date"  : dateFormattor,
  "datetime" : datetimeFormattor,
  "boolean" : booleanFormattor

And now our underscorejs solution, function(obj){ return formattor[obj.type](obj.value);});
It is really short and expressive code.

Normalize the data
In one of the scenario, we were dealing with large amount of data. And some time data list used to have nested array and it was causing the search too slow.  Our first implementation of search function had complexity of O(n) and it’s become O(n2) for another nested array and so on. It was so bad that, some time browser use to become unresponsive.
To overcome from this issue we decided to normalize the data array to single object and make elements unique property as key. And by doing this the search function complexity is reduce to perfect O(1).  Because after normalization we were simply accessing the property instead of find it.

For example if you want to get child “c2” in “p1” element then code will be: “data[‘p1’][‘c2’]”

Here is the raw data
var data = [{
 key: 'p1',
 name: 'parent-1',
 childs: [{key: 'c1',name: 'child-1'},{key: 'c2',name: 'child-2'},{key: 'c3',name: 'child-3'}]
 key: 'p2',
 name: 'parent-2',
 childs: [{key: 'c3',name: 'child-3'},{key: 'c4',name: 'child-4'},{key: 'c5',name: 'child-5'}]
 key: 'p3',
 name: 'parent-3',
 childs: [{key: 'c11',name: 'child-11'},{key: 'c12',name: 'child-12'},{key: 'c13',name: 'child-13'}]
 key: 'p4',
 name: 'parent-4',
 childs: [{key: 'c12',name: 'child-12'},{key: 'c14',name: 'child-14'},{key: 'c11',name: 'child-11'}]
 key: 'p5',
 name: 'parent-5',
 childs: [{key: 'c8',name: 'child-8'},{key: 'c1',name: 'child-1'},{key: 'c3',name: 'child-3'}]
 key: 'p6',
 name: 'parent-6'

And expected output after data normalization
 p1: {
  key: 'p1',
  name: 'parent-1',
  childs: {
   c1: {key: 'c1',name: 'child-1'},
   c2: {key: 'c2',name: 'child-2'},
   c3: {key: 'c3',name: 'child-3'}
var normalize = function(p1, p2){
    p1[p2.key] = p2;
    if(p2.childs){ p2.childs = _.reduce(p2.childs,normalize,{}); }
    return p1;

_.reduce(data, normalize, {});

Again it’s simple, small and readable code.

This is really elegant library with tons of utility functions as you start exploring it, you will find your project codebase much smaller and clean.

PS: Lo-Dash is a drop and replace library for underscorejs with extra features + performance + bug fixes.


Popular posts from this blog

ERROR: Ignored call to 'alert()'. The document is sandboxed, and the 'allow-modals' keyword is not set.

Recently I found this issue while writing code snippet in "JSFiddle". And after searching, found this was happening because of new feature added in "Chrome 46+". But at the same time Chrome doesn't have support for "allow-modals" property in "sandbox" attribute. Chromium issue for above behavior: To make it work you have to add "allow-scripts allow-modals" in "sandbox" attribute, and use "window.alert" instead of "alert". <!-- Sandbox frame will execute javascript and show modal dialogs --> <iframe sandbox="allow-scripts allow-modals" src="iframe.html"> </iframe> Feature added: Block modal dialog inside a sandboxed iframe. Link: Feature working Demo page:

Application Design Notes

Don’t be afraid to write your own code, but be absolutely sure you need to Don't reinvent the wheel Learn more about your libraries and take full advantage  Date time calculation is hard ( leap second ,  leap year ), use trusted library  js-joda ,  momentJs ,  joda (java) Simple is better than perfect (nearly) every time If you can deliver a sub-optimal solution (that solves the problem but has known limitation) in a week instead of a full featured one in a month DO, IT Simple system are Easy to reason about  Easy to debug Easy to refactor Easy to learn Simple doesn't mean you skip good engineering, but you can use duct tape. Build things the right way from the start, refactoring is hard and expensive Security Manage and store passwords securely Telemetry Common retrofitting "grunt work" Internationalization + localization Web Content Accessibility Factoring and styling HTML UI Adding unit test to an existing codebase LOG LOG LOG Log, but do it right We spend lot of t

How to store user password at server!!!

Trick is, you should never store user password… never ever. Now the real question is, then how to authenticate and authorize the user with password. And answer is when user enter the password, we should encrypt the password and store the hints. So next time when user enter the password we follow the same process and compare hints, if both hints are same then password is matched, else it is wrong password. Next question will be, what kind of hints, and how to generate these hints. In simple term hints are the obfuscated and fragmented form of user password. And very important part is hints generation process, which have to be collision resistant , means there will be very less possibility to find the data which generate same hints (like Cryptographic hashing functions ). Below is the simple checklist of password hashing and storing, which you should always keep in mind. PS You're Probably Storing Passwords Incorrectly Storing Passwords - done rig