Wednesday, May 22, 2013

Underscore is for querying collections.

I saw Mark DiMarco speak on D3 charting at AustinJS last night and while the talk really didn't have a primary focus to do with underscore.js, he brought it up in passing and I was fascinated. He said one may use pluck to pluck items out of a collection and put them into a new collection. I looked into Underscore and found that it is for doing LINQesque (think C#) queries in JavaScript. I downloaded the minimized production version and struggled to get pluck to work. I think it was wrong for what I was attempting. (Below I get all of the supreme court justices who vote Yay and just those justices listed in a dropdown list.) I eventually used filter instead of pluck but struggled in vain to get filter to return the keys of a dictionary-shaped hash in lieu of the values to an array. I eventually just made a backing store array and populated it as an extra step in the process. This is cool stuff.

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="utf-8">
      <title>Whatever</title>
      <link rel="stylesheet" type="text/css" href="styles.css" media="screen">
      <style type="text/css" media="all">
         #list {
            width: 220px;
         }
      </style>
   </head>
   <body>
      <select id="list">
         <option selected>change me to something else</option>
      </select>
      <script src="underscore-min.js" type="text/javascript"></script>
      <script type="text/javascript">
         var obj = new Object();
         obj['Alito'] = "Yay";
         obj['Breyer'] = "Nay";
         obj['Ginsburg'] = "Nay";
         obj['Kagan'] = "Yay";
         obj['Kennedy'] = "Yay";
         obj['Roberts'] = "Yay";
         obj['Scalia'] = "Yay";
         obj['Sotomayor'] = "Nay";
         obj['Thomas'] = "Yay";
         var yesmen = new Array();
         var yays = _.filter(obj, function(a,b) {
            if (a == 'Yay') yesmen.push(b);
            return a == 'Yay';
         });
         for (var i=0; i<yesmen.length; i++)
         {
            var opt = document.createElement("option");
            opt.text = yesmen[i];
            opt.value = yesmen[i];
            document.getElementById("list").options.add(opt);
         }
      </script>
   </body>
</html>

 
 

A random note for myself: By the way if I had just taken the original hash and displayed the yays and nays while using the names as the hidden value that would have looked like so.

for (item in obj)
{
   var opt = document.createElement("option");
   opt.text = obj[item];
   opt.value = item;
   document.getElementById("list").options.add(opt);
}

No comments:

Post a Comment