Home UnderscoreJS UnderscoreJS

UnderscoreJS

1165
0

Contents

  1. What is Underscore
  2. Setup Underscore
  3. Hello Underscore World
  4. Collection Functions
  5. Array & Object Functions
  6. Misc Functions

What data operations can it do?

  • Filters large data sets
  • Sorts and groups data
  • Transforms data to different formats
  • Format data using templates

What is Underscore

  • Underscore is a JS Library for data manipulation
  • Useful for performing common operations on data
  • Works with JSON objects and arrays
  • We’ll use it to manipulate JSON data sent to us via Ajax requests, etc.

Visit underscorejs.org
We’ll see:

  • download section
  • long list of underscore functions
  • all functions are preceded with the prefix _.
    • _.size()
    • _.find()
    • _.sortBy()

Get Development version
It’s just a .js file
Save it into a project folder in the htdocs folder

Hello Underscore World

HelloUnderscore.html

<!doctype html>
<html>
<head>
    <script type="text/javascript" src="underscore.js"></script>
</head>
<body>
<h1>Hello Underscore</h1>

<script type="text/javascript">
    var nums=[1,2,3];
    var obj={"name": "tom", "job": "Actor"};

    console.log("Array has " + _.size(nums) + " values");
    console.log("Object has " + _.size(obj) + " fields");
</script>
</body>
</html>

Callback Functions Revised

function tick()
{
    alert("hello");
}

var handle=setInterval(tick,1000);

// OR

var handle=setInterval(function(){
        alert("hello");
    },1000);

Some JavaScript functions have callback functions as parameters
Underscore functions use callback functions too

Collection/List Functions

  • These functions are available to view at the underscorej.org website
  • It’s not feasible or realistic to be shown them all
  • Using documentation for any library is itself a skill
  • You must learn how to use this documentation
  • There follows a brief description of some of these functions…
  • each()
  • size()
  • find()
  • findWhere()
  • pluck()
  • filter()
  • where()
  • sortBy()

Iteration with each()

See each() @ underscorejs.org

Underscore makes it easy to iterate over collections of data like:

  • arrays
  • objects

Previously, we’d used a for loop like this:

var nums = [1,2,3];

for(var i=0;i<nums.length;i++)
console.log(nums[i]);

With Underscore we can use the each() function:

_.each(nums, function(element){
console.log(element);
});

We’ll use the stations.js collection of objects this time
It’s a list of weather stations Met Eireann use throughout Ireland
Let’s print out the name of each station…

stationNames.html

<!doctype html>
<html>
<head>
<script type="text/javascript" src="underscore.js"></script>
<script type="text/javascript" src="stations.js"></script>
<script type="text/javascript">
_.each(stations, function(element) { 
console.log(element.name) 
});
</script> 
</head>

<body>
<h1>Stations</h1>

</body>
</html>

Let’s add content to main page this time…

stationNames2.html

<!doctype html>
<html>
<head>
<script type="text/javascript" src="underscore.js"></script>
<script type="text/javascript" src="stations.js"></script>
<script type="text/javascript">
window.onload=function(){
function printStationData(element,i){
var div=document.getElementById("data");
div.innerHTML = div.innerHTML + i + ": " + element.name + "<br>";
} 
_.each(stations, printStationData);
}
</script> 
</head>
<body>
<h1>Stations</h1>
<div id="data"></div>
</body>
</html>

Let’s keep separate the HTML and JavaScript…

stationNames3.html

<!doctype html>
<html>
<head>
<script type="text/javascript" src="underscore.js"></script>
<script type="text/javascript" src="stations.js"></script>
<script type="text/javascript" src="stationNames3.js"></script> 
</head>
<body>
<h1>Stations</h1>
<div id="data"></div>
</body>
</html>

stationNames3.js

window.onload=function(){
function printStationData(element,i)
{
var div=document.getElementById("data");
div.innerHTML = div.innerHTML + i + ": " + element.name + "<br>";
}

_.each(stations, printStationData);
}

List size with size()

<!doctype html>
<html>
<head>
    <script type="text/javascript" src="underscore.js"></script>
    <script type="text/javascript" src="stations.js"></script>
    <script type="text/javascript">
        console.log(_.size(stations));
    </script>   
</head>

<body>
<h1>Stations</h1>

</body>
</html>

See size() @ underscorejs.org
It returns the number of values in the list

Searching with find()

See find() @ underscorejs.org
It returns first value in list that matches a predicate (condition)
It returns undefined if no match is found

findStations.html

<!doctype html>
<html>
<head>
    <script type="text/javascript" src="underscore.js"></script>
    <script type="text/javascript" src="stations.js"></script>
    <script type="text/javascript" src="findStations.js"></script>  
</head>
<body>
<h1>Stations</h1>
<div id="data"></div>
</body>
</html>

findStations.js

window.onload=function(){
   function findStations(element)
   {
      if(element.county=="Donegal")
      return true;
   }

   var station=_.find(stations, findStations);
      if(station!=undefined)
   {
      var div = document.getElementById("data");
      div.innerHTML = div.innerHTML + station.name + " County " + station.county;
   }
}

Searching with findWhere()

See findWhere() @ underscorejs.org
It returns first value in list that matches all object key-value pairs
If no match is found undefined is returned

findWhereStations.html

<!doctype html>
<html>
<head>
<script type="text/javascript" src="underscore.js"></script>
<script type="text/javascript" src="stations.js"></script>
<script type="text/javascript" src="findWhereStations.js"></script> 
</head>
<body>
<h1>Stations</h1>
<div id="data"></div>
</body>
</html>

findWhereStations.js

window.onload=function(){
    var station=_.findWhere(stations, {name:"PhoenixPark", county:"Dublin"});
    if(station!=undefined)
    {
        var div = document.getElementById("data");
        div.innerHTML = div.innerHTML + station.name + " County " + station.county;
    }
}

Extracting with pluck()

See pluck() @ underscorejs.org
It extracts a list of values from a list of objects
A kind of vertical slicing of the dataset

pluckStations.html

<!doctype html>
<html>
<head>
    <script type="text/javascript" src="underscore.js"></script>
    <script type="text/javascript" src="stations.js"></script>
    <script type="text/javascript" src="pluckStations.js"></script> 
</head>
<body>
<h1>Stations</h1>
<div id="data"></div>
</body>
</html>

pluckStations.js

window.onload=function(){
    var stationNames=_.pluck(stations, "name");

    _.each(stationNames,function(element){
        var div = document.getElementById("data");
        div.innerHTML = div.innerHTML + element + "<br>";           
    });

}

Filtering with filter()

See filter() @ underscorejs.org
Filters a large collection of data down to a smaller collection
Uses a callback function

filterStations.html

<!doctype html>
<html>
<head>
    <script type="text/javascript" src="underscore.js"></script>
    <script type="text/javascript" src="stations.js"></script>
    <script type="text/javascript" src="filterStations.js"></script>    
</head>
<body>
<h1>Stations</h1>
<div id="data"></div>
</body>
</html>

filterStations.js

window.onload=function(){
    function getCountyStations(element)
    {
        if(element.county=="Donegal")
            return true;
    }
    var countyStations = _.filter(stations,getCountyStations);
    _.each(countyStations, function(element){
        var div = document.getElementById("data");
        div.innerHTML = div.innerHTML + element.name + "<br>";          
    });

}

Filtering with where()

See where() @ underscorejs.org
Filters a large collection of data down to a smaller collection
It returns a list that matches all object key-value pairs
No use of callback functions

whereStations.html

<!doctype html>
<html>
<head>
    <script type="text/javascript" src="underscore.js"></script>
    <script type="text/javascript" src="stations.js"></script>
    <script type="text/javascript" src="whereStations.js"></script> 
</head>
<body>
<h1>Stations</h1>
<div id="data"></div>
</body>
</html>

whereStations.js

window.onload=function(){
    var countyStations = _.where(stations,{"county":"Donegal"});
    _.each(countyStations, function(element){
        var div = document.getElementById("data");
        div.innerHTML = div.innerHTML + element.name + "<br>";          
    });

}

Sorting with sortBy()

See sortBy() @ underscorejs.org
Sorts collection of data by a particular field/key
Uses a callback functions

sortByStations.html

<!doctype html>
<html>
<head>
    <script type="text/javascript" src="underscore.js"></script>
    <script type="text/javascript" src="stations.js"></script>
    <script type="text/javascript" src="sortByStations.js"></script>    
</head>
<body>
<h1>Stations</h1>
<div id="data"></div>
</body>
</html>

sortByStations.js

window.onload=function(){
    function sortByName(element)
    {
        return element.name;
    }

    var sorted = _.sortBy(stations,sortByName);
    _.each(sorted, function(element){
        var div = document.getElementById("data");
        div.innerHTML = div.innerHTML + element.name + "<br>";          
    });
}

Group with groupBy()

SKIP!!

See groupBy() @ underscorejs.org
Groups collection of data by a particular field/key
Returns groupings as an associative array …

Associative Arrays

Many programming languages support arrays with named indexes
Arrays with named indexes are called associative arrays
Underscore uses associative arrays
JavaScript does not!
An example…

var food = {
    Fruit: [0: {name: 'apples'} , 1: {name: 'pears'}, 2: {name: 'oranges'}],
    Vegatable: [0: {name: 'carrot'}, 1: {name: 'potato'}]
}
for(i in food)
    console.log(i);  // prints Fruit and Vegatable

Grouping with groupBy()

groupByStations.html

<!doctype html>
<html>
<head>
    <script type="text/javascript" src="underscore.js"></script>
    <script type="text/javascript" src="stations.js"></script>
    <script type="text/javascript" src="groupByStations.js"></script>   
</head>
<body>
<h1>Stations</h1>
<div id="data"></div>
</body>
</html>

groupByStations.js

window.onload=function()
{
    function groupByCounty(element)
    {
        return element.county;
    }

    var grouped = _.groupBy(stations,groupByCounty);

    console.log(grouped);
    console.log(grouped['Carlow']);
    for(i in grouped)
        console.log(i);

    for(i in grouped)
    {
        _.each(grouped[i], function(element){
            var div = document.getElementById("data");
            div.innerHTML = div.innerHTML + i + ":" + element.name + "<br>";        
        });
    }
}

Array & Object Functions

Underscore can manipulate JS arrays and objects too
Some array functions:

  • first()
  • last()
  • initial()
  • rest()

Some object functions:

  • keys()
  • values()

Misc Functions

  • uniqueId()
  • max() and min()
  • contains()
  • random()
  • times()
Previous articleMustacheJS
Next articleSoftware Quality W02 & Review