js计算数组中元素出现的次数,并实现去重

希望最后能得到去重的数组,和每一个元素出现的次数

达令说
浏览 797回答 1
1回答

开满天机

如果期望排序根据数值el来的话使用这个:把count改成el即可!function getCount(arr, rank,ranktype){&nbsp;&nbsp; &nbsp; var obj = {}, k, arr1 = [];&nbsp; &nbsp; for (var i = 0, len = arr.length; i < len; i++) {&nbsp; &nbsp; &nbsp; &nbsp; k = arr[i];&nbsp; &nbsp; &nbsp; &nbsp; if (obj[k])&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; obj[k]++;&nbsp; &nbsp; &nbsp; &nbsp; else&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; obj[k] = 1;&nbsp; &nbsp; }&nbsp; &nbsp; //保存结果{el-'元素',count-出现次数}&nbsp; &nbsp; for (var o in obj) {&nbsp; &nbsp; &nbsp; &nbsp; arr1.push({el: o, count: obj[o]});&nbsp; &nbsp; }&nbsp; &nbsp; //排序(降序)&nbsp; &nbsp; arr1.sort(function (n1, n2) {&nbsp; &nbsp; &nbsp; &nbsp; return n2.el - n1.el&nbsp; &nbsp; });&nbsp; &nbsp; //如果ranktype为1,则为升序,反转数组&nbsp; &nbsp; if(ranktype===1){&nbsp; &nbsp; &nbsp; &nbsp; arr1=arr1.reverse();&nbsp; &nbsp; }&nbsp; &nbsp; var rank1 = rank || arr1.length;&nbsp; &nbsp; return arr1.slice(0,rank1);}getCount([2,2,3,1],null,1)//传参(ranktype=1,rank=null),升序返回所有元素出现次数function getCount(arr, rank,ranktype){&nbsp;&nbsp; &nbsp; var obj = {}, k, arr1 = [];&nbsp; &nbsp; for (var i = 0, len = arr.length; i < len; i++) {&nbsp; &nbsp; &nbsp; &nbsp; k = arr[i];&nbsp; &nbsp; &nbsp; &nbsp; if (obj[k])&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; obj[k]++;&nbsp; &nbsp; &nbsp; &nbsp; else&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; obj[k] = 1;&nbsp; &nbsp; }&nbsp; &nbsp; //保存结果{el-'元素',count-出现次数}&nbsp; &nbsp; for (var o in obj) {&nbsp; &nbsp; &nbsp; &nbsp; arr1.push({el: o, count: obj[o]});&nbsp; &nbsp; }&nbsp; &nbsp; //排序(降序)&nbsp; &nbsp; arr1.sort(function (n1, n2) {&nbsp; &nbsp; &nbsp; &nbsp; return n2.count - n1.count&nbsp; &nbsp; });&nbsp; &nbsp; //如果ranktype为1,则为升序,反转数组&nbsp; &nbsp; if(ranktype===1){&nbsp; &nbsp; &nbsp; &nbsp; arr1=arr1.reverse();&nbsp; &nbsp; }&nbsp; &nbsp; var rank1 = rank || arr1.length;&nbsp; &nbsp; 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),只返回出现次数排序(升序)前三的
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript