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.

Feature working Demo page:

JavaScript [ExtJs3]: EditorGridPanel Read-Only (dynamically)

Many time we face the scenerio where we have to make the editor grid read-only dynamically.

Ext.override(Ext.ux.grid.CheckColumn, { editable: true, onMouseDown: function (e, t) { if ( { e.stopEvent(); var me = this, grid = me.grid, view = grid.getView(), index = view.findRowIndex(t), colindex = view.findCellIndex(t), record =; if (!grid.isReadOnly && grid.colModel.isCellEditable(colindex, index)) { record.set(me.dataIndex, ![me.dataIndex]); } } } }); var grid = new Ext.grid.EditorGridPanel({ ... isReadOnly: true, //set to flag to make check column readonly ... }); //to make other column readonly grid.on('beforeedit', function () { return false; });

JavaScript [ExtJs3]: Total “Record” count in filtered store

There is two way to get record count from the Store
store.getTotalCount() This function depend on server response value. For accuracy of the value, property shell if return by the server.

Property name for the diff. reader:
totalProperty for JsonReader, totalRecords for XmlReaderstore.getCount() Will return you the number of record from the store.
Or if you have filter on the store, it will give you the number of filtered record.
But if you want to get the total number of record regardless filtering, Then it will be like this

var totalRecords = store.snapshot ? store.snapshot.length : store.getCount();
“snapshot” is the variable in “Store” which hold the actual data in case if you have applied a filter.