特定ユーザーのQiita記事一覧を得る(3)

[前回の記事](https://qiita.com/ELIXIR/items/dcdab71d6c81ea5a82f2)のアップデートです。
出現回数が多いタグの順にソートするようにしました。
[次の記事](https://qiita.com/ELIXIR/items/5972aec6833504293e45)

[動作デモ](https://elix.jp/app/tools/qiita_index.html?uuid=ELIXIR)
前回同様ローカル環境でも動作します。

結果：
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/59911/3e888e67-5ba4-b290-38fd-a23a651a90e6.png)

名前順にソートしたい場合は
```sortButtons(true);```
をfalseにします。

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/59911/e83089f4-52a3-f125-e1f1-4954894c5f11.png)

```[myindex.html]
<!DOCTYPE html>
<html><head><title>Qiita index</title>
    <style type="text/css">
      .cOnButton { color: #111; background-color: #fc8; }
      .cOffButton { color: #888; }
      button{ margin: 1px; height: 30px; font-size: 1rem;}
    </style>
    <script>
    var USER_ID='ELIXIR'; // 自分のuser_idに変えてください
    const PAR_PAGE=100; // Qiita API の上限
    var resArr = [];
    var existTagArr = [];

    var TmGetUrlVarByKeys = function(){
      var vars = {}; 
      var param = location.search.substring(1).split('&');
      for(var i = 0; i < param.length; i++) {
          var keySearch = param[i].search(/=/);
          var key = '';
          if(keySearch != -1) key = param[i].slice(0, keySearch);
          var val = param[i].slice(param[i].indexOf('=', 0) + 1);
          if(key != '') vars[key] = decodeURI(val);
      } 
      return vars; 
    }

    function onLoad(){
      var vars = TmGetUrlVarByKeys();
      if(!(typeof vars["uuid"] === "undefined")) { document.getElementById('iUuid').value = vars["uuid"]; };
    }
    function onSearch(){
      resArr = [];
      USER_ID = document.getElementById('iUuid').value;
      document.title=USER_ID;

      getUser();
    }

    function apiCall(_api, _callback, _userData=0){
      var req = new XMLHttpRequest();
      req.responseType="json";
      req._userData=_userData;
      req.addEventListener("load", _callback);
      req.open('GET', 'https://qiita.com/api/v2/'+_api, true);
      req.send();
    }

    function getUser(){
      apiCall('users/'+USER_ID,function(){
        if(this.response["items_count"]==undefined)
          document.getElementById('iResult').innerHTML = 'エラーまたはapi使用上限(60回/時間)に達しました。';
        else
          getData(Math.floor((this.response["items_count"]+(PAR_PAGE-1))/PAR_PAGE));
      });
    }

    function getData(_page=1){
      apiCall('users/'+USER_ID+'/items?per_page='+PAR_PAGE+'&page='+_page,function(){
        resArr=resArr.concat(this.response);
        if(this._userData>1)
          getData(this._userData-1);
        else
          dispData(resArr);
      },_page);
    }

    function sortButtons(_sortByCount=false){
      var buttonsEle = document.getElementById('iButtons');
      var btnArr = Array.from(document.getElementById('iButtons').children);
      btnArr.sort(
        function(v0,v1){
          if(_sortByCount){
            return (v0.existCnt > v1.existCnt) ? -1:1;
          }else{
            return (v0.innerText < v1.innerText) ? -1:1;
          }
        }
      );
      buttonsEle.innerHTML="";
      for(var i=0;i<btnArr.length;++i){
        buttonsEle.appendChild(btnArr[i]);
      }
    }
    function createButton(_name,_tag){
      existTagArr.push(_name);
      var btn = document.createElement('button');
      btn.innerHTML=_name;
      btn.className=(_name==_tag)?'cOnButton':'cOffButton';
      btn.onclick=function(){dispData(resArr,_name);}
      btn.id = 'i_btn'+_name;
      btn.existCnt=1;
      return btn;
    }
    function createButtons(_resArr,_tag){
      var buttonsEle = document.getElementById('iButtons');
      existTagArr=[];
      buttonsEle.innerHTML = '';
      for(var i=0;i<_resArr.length;++i){
        var tagArr=_resArr[i]['tags'];
        for(var j=0;j<tagArr.length;++j){
          if(!existTagArr.includes(tagArr[j]['name'])){
            buttonsEle.appendChild(createButton(tagArr[j]['name'],_tag));
          }else{
            document.getElementById('i_btn'+tagArr[j]['name']).existCnt+=1;
          }
        }
      }
      sortButtons(true);  //false if sort by name
    }

    function articleContainsTag(_article,_tag){
      for(var i=0;i<_article['tags'].length;++i)
          if(_article['tags'][i]['name']==_tag)
            return true;
        return false;
    }

    function dispData(_resArr,_tag=""){
      createButtons(_resArr,_tag);
      var str="";
      for(var i=0;i<_resArr.length;++i){
        if((_tag=="")||(articleContainsTag(_resArr[i],_tag)))
          str += '<a href="'+_resArr[i]['url']+'" target="_blank">'+ _resArr[i]['title']+'</a><br/>';
      }
      document.getElementById('iResult').innerHTML = str;
    }

  </script>
</head>
<body onload="onLoad()">
user_id@<input id="iUuid" type="text"> <input type="button" value="search" onclick="onSearch()"><div id="iButtons"></div><div id="iResult"></div></body>
<br/>
<!-- ad -->
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- WebCardGame00 -->
<ins class="adsbygoogle"
     style="display:block"
     data-ad-client="ca-pub-3504902108000381"
     data-ad-slot="6987101050"
     data-ad-format="auto"
     data-full-width-responsive="true"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
<!-- ad -->
</html>
```