function getCount(arr, rank,ranktype){ var obj = {}, k, arr1 = []; for (var i = 0, len = arr.length; i < len; i++) { k = arr[i]; if (obj[k]) obj[k]++;... ...
function getCount(arr, rank,ranktype){ var obj = {}, k, arr1 = []; for (var i = 0, len = arr.length; i < len; i++) { k = arr[i]; if (obj[k]) obj[k]++; else obj[k] = 1; } //保存結果{el-'元素',count-出現次數} for (var o in obj) { arr1.push({el: o, count: obj[o]}); } //排序(降序) arr1.sort(function (n1, n2) { return n2.count - n1.count }); //如果ranktype為1,則為升序,反轉數組 if(ranktype===1){ arr1=arr1.reverse(); } var rank1 = rank || arr1.length; return arr1.slice(0,rank1); } getCount([1,2,3,1,2,5,2,4,1,2,6,2,1,3,2])//預設情況,返回所有元素出現的次數 getCount([1,2,3,1,2,5,2,4,1,2,6,2,1,3,2],3)//傳參(rank=3),只返回出現次數排序前三的 getCount([1,2,3,1,2,5,2,4,1,2,6,2,1,3,2],null,1)//傳參(ranktype=1,rank=null),升序返回所有元素出現次數 getCount([1,2,3,1,2,5,2,4,1,2,6,2,1,3,2],3,1)//傳參(rank=3,ranktype=1),只返回出現次數排序(升序)前三的