Contents
What is Underscore
Setup Underscore
Hello Underscore World
Collection Functions
Array & Object Functions
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>
Do Underscore Ex 1
Complete ALL the exercises in this section.
Download Underscore development version from underscore.org .
Save it in a new folder called underscore in your htdocs folder.
Create and save the program helloUnderscore.html below into the underscore folder:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="underscore.js"></script>
</head>
<body>
<h1>Hello Underscore</h1>
Check the console window. There should be no errors.
<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>
Open it using your browser.
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:
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
Do Underscore Ex 2
Complete ALL the exercises in this section.
1. Download the players.js JSON data file. Save it in the folder called underscore in your htdocs folder.
2. Save the program playerNames.html below into the underscore folder:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="underscore.js"></script>
<script type="text/javascript" src="players.js"></script>
<script type="text/javascript" src="playerNames.js"></script>
</head>
<body>
<h1>Players</h1>
<div id="data"></div>
</body>
</html>
3. Save the program playerNames.js below into the underscore folder:
window.onload=function(){
// add your code here
}
4. Using the Underscore each() function update playerNames.js to print the name of every player. Use a <br> tag to separate each name.
5. Attempt to have each players name appear inside a HTML table as shown here:
Q5 – Players
6. Update the <h1> heading content in the HTML page to print the number of players like this:
Q6 – Players
Solution - Q4
playerNames.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="underscore.js"></script>
<script type="text/javascript" src="players.js"></script>
<script type="text/javascript" src="playerNames.js"></script>
</head>
<body>
<h1 id="header">Players</h1>
<div id="data">
</div>
</body>
</html>
playerNames.js
window.onload = function() {
function printPlayerData(element, i) {
var div = document.getElementById("data");
div.innerHTML = div.innerHTML + i + ": " + element.Name + "<br>";
}
_.each(players, printPlayerData);
}
Solution - Q5
playerNames.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="underscore.js"></script>
<script type="text/javascript" src="players.js"></script>
<script type="text/javascript" src="playerNames.js"></script>
</head>
<body>
<h1 id="header">Players</h1>
<table id="data" border="1">
</table>
</body>
</html>
playerNames.js
window.onload = function() {
function printPlayerData(element, i) {
var div = document.getElementById("data");
div.innerHTML = div.innerHTML + "<td>" + element.Name + "</td>";
}
_.each(players, printPlayerData);
}
Solution - Q6
playerNames.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="underscore.js"></script>
<script type="text/javascript" src="players.js"></script>
<script type="text/javascript" src="playerNames.js"></script>
</head>
<body>
<h1 id="header">Players</h1>
<table id="data" border="1">
</table>
</body>
</html>
playerNames.js
window.onload = function() {
function printPlayerData(element, i) {
var div = document.getElementById("data");
div.innerHTML = div.innerHTML + "<td>" + element.Name + "</td>";
}
_.each(players, printPlayerData);
var div2 = document.getElementById("header");
div2.innerHTML = _.size(players) + " Players";
}
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;
}
}
Do Underscore Ex 3 - Part 1
Complete ALL the exercises in this section. If you need a solution just ask.Complete ALL the exercises in this section.
If you need a solution just ask.
Part 1 – find()
1. Save the program playerFind.html below into the underscore folder:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="underscore.js"></script>
<script type="text/javascript" src="players.js"></script>
<script type="text/javascript" src="playerFind.js"></script>
</head>
<body>
<h1>Players</h1>
<button id="findButton">Show All</button><hr>
<div id="data"></div>
</body>
</html>
2. Save the program playerFind.js below into the underscore folder:
window.onload=function()
{
document.getElementById('findButton').onclick=function()
{
// add code here to react to button click
}
}
3. When the button is clicked add code to display all the player names on separate lines.
4. Change the caption of the button to “Find Bravo”. Modify the code so when the button is pressed now use the find() function to find and display only the player called “Bravo”.
5. What happens if you try to find a player whos name does not exist? Ensure no console errors appear.
6. Add a text box before the Find button as shown here:
Find Players
Update your code so you can search for any player’s name typed into this box.
Only search when Find button is pressed.
7. Attempt to implement the search so that as you type text the fist player name that matches the current text in the textbox is shown. You’ll need to use the onkeyup event and use the JavaScript function include() in your solution.
Solution - Part 1 - Q3
playerFind.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="underscore.js"></script>
<script type="text/javascript" src="players.js"></script>
<script type="text/javascript" src="playerFind.js"></script>
</head>
<body>
<h1>Players</h1>
<button id="findButton">Show All</button><hr>
<div id="data"></div>
</body>
</html>
playerFind.js
window.onload=function()
{
document.getElementById('findButton').onclick=function()
{
// add code here to react to button click
function printPlayerData(element, i) {
var div = document.getElementById("data");
div.innerHTML = div.innerHTML + i + ": " + element.Name + "<br>";
//div.innerHTML = div.innerHTML + "<td>" + element.Name + "</td>";
}
_.each(players, printPlayerData);
}
}
Solution - Part 1 - Q4
playerFind.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="underscore.js"></script>
<script type="text/javascript" src="players.js"></script>
<script type="text/javascript" src="playerFind.js"></script>
</head>
<body>
<h1>Players</h1>
<button id="findButton">Find Bravo</button><hr>
<div id="data"></div>
</body>
</html>
playerFind.js
window.onload=function()
{
document.getElementById('findButton').onclick=function()
{
function findPlayers(element)
{
if(element.Name=="Bravo")
return true;
}
var player = _.find(players, findPlayers);
var div = document.getElementById("data");
div.innerHTML = div.innerHTML + player.Name;
}
}
Solution - Part 1 - Q5
playerFind.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="underscore.js"></script>
<script type="text/javascript" src="players.js"></script>
<script type="text/javascript" src="playerFind.js"></script>
</head>
<body>
<h1>Players</h1>
<button id="findButton">Find Bravo</button><hr>
<div id="data"></div>
</body>
</html>
playerFind.js
window.onload=function()
{
document.getElementById('findButton').onclick=function()
{
function findPlayers(element)
{
if(element.Name=="Bravo")
return true;
}
var player = _.find(players, findPlayers);
if(player!=undefined)// if statement ensures no console errors when player does not exist
{
var div = document.getElementById("data");
div.innerHTML = div.innerHTML + player.Name;
}
}
}
Solution - Part 1 - Q6
playersFind.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="underscore.js"></script>
<script type="text/javascript" src="players.js"></script>
<script type="text/javascript" src="playerFind.js"></script>
</head>
<body>
<h1>Players</h1>
Find: <input type = "text" id="find">
<button id="findButton">Find</button><hr>
<div id="data"></div>
</body>
</html>
playerFind.js
window.onload=function()
{
document.getElementById('findButton').onclick=function()
{
var div = document.getElementById("data");//these 2 lines
div.innerHTML = "";//clear the div box for new result
var value = document.getElementById("find").value;
function findPlayers(element) {
if(element.Name == value)
return true;
}
var player = _.find(players, findPlayers);
if(player!=undefined)// if statement ensures no console errors when player does not exist
{
var div = document.getElementById("data");
div.innerHTML = div.innerHTML + player.Name;
}
}
}
Solution - Part 1 - Q7
playerFind.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="underscore.js"></script>
<script type="text/javascript" src="players.js"></script>
<script type="text/javascript" src="playerFind.js"></script>
</head>
<body>
<h1>Players</h1>
Find:
<input type = "text" id = "find" onkeyup = "searchPlayer()">
<hr>
<div id="data"></div>
</body>
</html>
playerFind.js
function searchPlayer()
{
var value = document.getElementById("find").value;
function findPlayers(element) {
if(element.Name.includes(value))
return true;
}
var player = _.find(players, findPlayers);
if(player!=undefined)// if statement ensures no console errors when player does not exist
{
var div = document.getElementById("data");
//div.innerHTML = div.innerHTML + player.Name;
document.getElementById("data").innerHTML = value;
}
}
Do Underscore Ex 3 - Part 2
Complete ALL the exercises in this section. If you need a solution just ask.
Part 2 – findWhere()
1. Save the program playerWhere.html below into the underscore folder:
<!doctype html>
<html>
<head>
<script type="text/javascript" src="underscore.js"></script>
<script type="text/javascript" src="players.js"></script>
<script type="text/javascript" src="playerWhere.js"></script>
</head>
<body>
<h1>Players</h1>
<table>
<tr>
<td>Team:</td><td><input id="team" type="text"></td>
</tr>
<tr>
<td>Position:</td><td><input id="position" type="text"></td>
</tr>
<tr>
<td></td><td><button id="findButton">Find</button></td>
</tr>
</table>
<hr>
<div id="data"></div>
</body>
</html>
2. Save the program playerWhere.js below into the underscore folder:
window.onload=function()
{
document.getElementById('findButton').onclick=function()
{
// add code here to react to button click
var details = new Object();
details.Team = ...
details.Position = ...
// use findWhere() function here
}
}
3. When viewing playerWhere.html it should have 2 text boxes and a find button:
Solution - Part 2 - Q3
playerWhere.html
<!doctype html>
<html>
<head>
<script type="text/javascript" src="underscore.js"></script>
<script type="text/javascript" src="players.js"></script>
<script type="text/javascript" src="playerWhere.js"></script>
</head>
<body>
<h1>Players</h1>
<table>
<tr>
<td>Team:</td><td><input id="team" type="text"></td>
</tr>
<tr>
<td>Position:</td><td><input id="position" type="text"></td>
</tr>
<tr>
<td></td><td><button id="findButton">Find</button></td>
</tr>
</table>
<hr>
<div id="data"></div>
</body>
</html>
playerWhere.js
window.onload=function()
{
document.getElementById('findButton').onclick=function()
{
// add code here to react to button click
var plyrTeam = document.getElementById("team").value;
var plyrPosition = document.getElementById("position").value;
var details = new Object();
details.Team = plyrTeam;
details.Position = plyrPosition;
// use findWhere() function
var player = _.findWhere(players, details);
if(player != undefined)
{
var div = document.getElementById("data");
div.innerHTML = div.innerHTML + player.Name;
}
}
}
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>";
});
}
Do Underscore Ex 4 - Part 1
Part 1 – filter()
1. Save the program playerFilter.html below into the underscore folder:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="underscore.js"></script>
<script type="text/javascript" src="players.js"></script>
<script type="text/javascript" src="playerFilter.js"></script>
</head>
<body>
<h1>Players by Position</h1>
<select id="position">
<option value=''>Select...</option>
<option value='All'>All</option>
<option value='Goalkeeper'>Goalkeeper</option>
<option value='Defender'>Defender</option>
<option value='Midfielder'>Midfielder</option>
<option value='Forward'>Forward</option>
</select>
<hr>
<div id="data"></div>
</body>
</html>
2. Save the program playerFilter.js below into the underscore folder:
window.onload=function()
{
document.getElementById('position').onchange=function()
{
// add code here to react to dropdown selection
}
}
3. When the dropdown box is selected add code to filter by position and display all the player names on separate lines.
Solution - Part 1 - Q3
playerFilter.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="underscore.js"></script>
<script type="text/javascript" src="players.js"></script>
<script type="text/javascript" src="playerFilter.js"></script>
</head>
<body>
<h1>Players by Position</h1>
<select id="position">
<option value=''>Select...</option>
<option value='All'>All</option>
<option value='Goalkeeper'>Goalkeeper</option>
<option value='Defender'>Defender</option>
<option value='Midfielder'>Midfielder</option>
<option value='Forward'>Forward</option>
</select>
<hr>
<div id="data"></div>
</body>
</html>
playerFilter.js
window.onload=function()
{
document.getElementById('position').onchange=function()
{
var position = document.getElementById("position").value;
var div = document.getElementById("data");
function playerPosition(element)
{
if(element.Position == position)
return true;
}
var playerPosition = _.filter(players, playerPosition);
div.innerHTML = "";
_.each(playerPosition, function(element) {
div.innerHTML = div.innerHTML + element.Name + "<br>";
});
if(position == "All")//to display all instead of filtering
{
_.each(players, function(element) {
div.innerHTML = div.innerHTML + element.Name + "<br>";
});
}
}
}
Do Underscore Ex 4 - Part 2
Part 2 – where()
1. Save the program playerFilter2.html below into the underscore folder:
<!doctype html>
<html>
<head>
<script type="text/javascript" src="underscore.js"></script>
<script type="text/javascript" src="players.js"></script>
<script type="text/javascript" src="playerFilter2.js"></script>
</head>
<body>
<h1>Players by Team & Position</h1>
Team:<select id="team">
<option value='ARS'>ARS</option>
<option value='BHA'>BHA</option>
<option value='BOU'>BOU</option>
<option value='BUR'>BUR</option>
<option value='CHE'>CHE</option>
<option value='CPL'>CPL</option>
<option value='EVE'>EVE</option>
<option value='HUD'>HUD</option>
<option value='LEI'>LEI</option>
<option value='LIV'>LIV</option>
<option value='MCI'>MCI</option>
<option value='MUN'>MUN</option>
<option value='NEW'>NEW</option>
<option value='SOT'>SOT</option>
<option value='STK'>STK</option>
<option value='SWA'>SWA</option>
<option value='TOT'>TOT</option>
<option value='WAT'>WAT</option>
<option value='WBA'>WBA</option>
<option value='WHU'>WHU</option>
</select>
Positon:<select id="position">
<option value='Goalkeeper'>Goalkeeper</option>
<option value='Defender'>Defender</option>
<option value='Midfielder'>Midfielder</option>
<option value='Forward'>Forward</option>
</select>
<hr>
<div id="data"></div>
</body>
</html>
2. Create the program file playerFilter2.js in the underscore folder
3. When either of the dropdown boxes are selected filter by team AND position and display all the player names on separate lines.
Solution - Part 2 - Q3
playerFilter2.html
<!doctype html>
<html>
<head>
<script type="text/javascript" src="underscore.js"></script>
<script type="text/javascript" src="players.js"></script>
<script type="text/javascript" src="playerFilter2.js"></script>
</head>
<body>
<h1>Players by Team & Position</h1>
Team:<select id="team" onchange="">
<option value='ARS'>ARS</option>
<option value='BHA'>BHA</option>
<option value='BOU'>BOU</option>
<option value='BUR'>BUR</option>
<option value='CHE'>CHE</option>
<option value='CPL'>CPL</option>
<option value='EVE'>EVE</option>
<option value='HUD'>HUD</option>
<option value='LEI'>LEI</option>
<option value='LIV'>LIV</option>
<option value='MCI'>MCI</option>
<option value='MUN'>MUN</option>
<option value='NEW'>NEW</option>
<option value='SOT'>SOT</option>
<option value='STK'>STK</option>
<option value='SWA'>SWA</option>
<option value='TOT'>TOT</option>
<option value='WAT'>WAT</option>
<option value='WBA'>WBA</option>
<option value='WHU'>WHU</option>
</select>
Positon:<select id="position">
<option value='Goalkeeper'>Goalkeeper</option>
<option value='Defender'>Defender</option>
<option value='Midfielder'>Midfielder</option>
<option value='Forward'>Forward</option>
</select>
<hr>
<div id="data"></div>
</body>
</html>
playerFilter2.js
window.onload=function()
{
var plyrTeam = document.getElementById("team").value;
var plyrPosition = document.getElementById("position").value;
var player = _.where(players, {"Team" : plyrTeam, "Position" : plyrPosition});
if(player!=undefined)// if statement ensures no console errors when player does not exist
{
var div = document.getElementById("data");
_.each(player, function(element) {
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>";
});
}
}
Do Underscore Ex 5
Part 1 – sortBy()
1. Save the program playerSort.html below into the underscore folder:
<!doctype html>
<html>
<head>
<script type="text/javascript" src="underscore.js"></script>
<script type="text/javascript" src="players.js"></script>
<script type="text/javascript" src="playerSort.js"></script>
</head>
<body>
<h1>Players by Team & Position</h1>
Sort by :<select id="sortBy">
<option value='Name'>Name</option>
<option value='Team'>Team</option>
</select>
<hr>
<div id="data"></div>
</body>
</html>
2. Create the program file playerSort.js in the underscore folder
3. When either of the dropdown boxes are selected sort by name or team and display all the player names and team on separate lines.
4. When you choose sort by team, attempt to sort the players name for that team too.
Solution
playerSort.html
<!doctype html>
<html>
<head>
<script type="text/javascript" src="underscore.js"></script>
<script type="text/javascript" src="players.js"></script>
<script type="text/javascript" src="playerSort.js"></script>
</head>
<body>
<h1 id="header">Players by Team & Position</h1>
Sort by :<select id="playerSort">
<option value='Name'>Name</option>
<option value='Team'>Team</option>
</select>
<hr>
<div id="data"></div>
</body>
</html>
playerSort.js
window.onload=function(){
function playerSort(element)
{
return element.name;
}
var sorted = _.sortBy(players,playerSort);
_.each(sorted, function(element){
var div = document.getElementById("data");
div.innerHTML = div.innerHTML + element.name + "<br>";
});
}
Array & Object Functions
Underscore can manipulate JS arrays and objects too
Some array functions:
first()
last()
initial()
rest()
Some object functions:
Misc Functions
uniqueId()
max() and min()
contains()
random()
times()