union, uniq, key, value

集合演算に関するメソッド

      <script>
        (function(){
          
          var a = [1, 2, 5];
          var b = [5, 2, 8];
          var x;

          // x = _.union(a, b);
          // x = _.intersection(a, b);
          // x = _.difference(a, b);
          x = _.uniq([2, 5, 2, 10, 5]);

          console.log(x);

        })();
      </script>

オブジェクト判定のメソッド

      <script>
        (function(){
          
          var x;
          var user = {
            name: 'yamamoto',
            score: 88,
            web: 'http://google.com'
          };

          // x = _.keys(user);
          // x = _.values(user);
          // x = _.invert(user);
          x = _.has(user, "name");
          // isEmpty, isString, isNull, isNumber
          console.log(x);

        })();
      </script>

データ生成のメソッド

        (function(){
          
          var x;
          
          // x = _.range(1, 11, 2);
          x = _.random(10);

          console.log(x);

        })();

メソッドをつなげるchainとvalue

      <script>
        (function(){
          
          var x;
          
          var a = [2, 5, 10, 8];
          x = _.chain(a)
              .shuffle()
              .map(function(num){
                return num * 2;
              })
              .value();

          console.log(x);

        })();
      </script>

underscore.js

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <title>Underscore.js</title>
  </head>
  <body>
      <script src="underscore-min.js"></script>
      <script>
        (function(){
          var x;
          x = _.shuffle([2, 8, 10, 3]);
          console.log(x);
        })();
      </script>
  </body>
</html>

eachとmap

<script src="underscore-min.js"></script>
      <script>
        (function(){
          /*
          _.each([2, 5, 8], function(num)){
              console.log(num * 2);
          });
          */

          var x = _.map([2, 5, 8], function(num){
              return num * 2;
          });
          console.log(x);

        })();
      </script>

find,filter,contain

      <script>
        (function(){
          
          var a = [2, 5, 8, 42, 12];
          var x;
          /*
          x = _.find(a, function(num){
            return num > 5;
          });
          */
          /*
          x = _.filter(a, function(num){
            return num > 5;
          });
          */
          x = _.contains(a, 10);
          console.log(x);

        })();
      </script>

groupBy, countBy

      <script>
        (function(){
          
          var a = [1, 2, 5, 8, 42, 12];
          var x;
          /*
          x = _.groupBy(a, function(num){
            return num % 3;
          })
          x = _.countBy(a, function(num){
              return num % 2 == 0 ? 'even' : 'odd';
          });
          */
          x = _.sortBy(a, function(num){
              return Math.sin(num);
          });

          console.log(x);

        })();
      </script>