一个随时更新的方法库
1.filter可在return 里加入限制条件,不修改原数组
let data = this.data let arr_filter = data.filter(function(element,index,self){ return element.post_fix=='apk'; //返回一个元素里的post_fix的值全是apk的数组 }) console.log(arr_filter)
2.filter去除undefiend项
this.listAll = this.listAll.filter(item => item)
3.一个n-m的随机数
random(min,max){ return Math.floor(Math.random() * (max - min)) + min; },
4.输出数组相同元素的个数,好像还能去重(全局暴露)
export function unique (arr) { var resultObj = {}; var result = []; var result2 = []; for(var i=0; i<arr.length; i++){ if(result.indexOf(arr[i]) == -1){ result.push(arr[i]); }else{ if(result2.indexOf(arr[i]) == -1){ result2.push(arr[i]); } } } var obj = {} arr.forEach((v,k)=>{ if(obj[v]){ obj[v]++; }else{ obj[v] = 1; } }); resultObj.result = result; resultObj.result2 = result2; resultObj.obj = obj; return {resultObj} }
5.输出数组相同元素的个数(可以排序),这个比上边方法好,转载自
<script> 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); } console.log(getCount([1,2,3,1,2,5,2,4,1,2,6,2,1,3,2]))//降序,全部 console.log(getCount([1,2,3,1,2,5,2,4,1,2,6,2,1,3,2],3))//传参(rank=3),降序,前三 console.log(getCount([1,2,3,1,2,5,2,4,1,2,6,2,1,3,2],null,1))//传参(rank=null,ranktype=1),升序,全部 console.log(getCount([1,2,3,1,2,5,2,4,1,2,6,2,1,3,2],3,1))//传参(rank=3,ranktype=1),升序,前三 </script>
6.数组对象按某个属性值排序(count,替换x,y位置改变升序降序)
goalsUP(x,y){ return x.count-y.count; },
使用:
let arr = arr.sort(this.goalsUP)
写法:let arr2 = arr.sort((a, b) =>b-a)