您现在的位置是:首页 > 文章详情

前端进阶|第十天 数组分组编程,区间还是连续一网打尽

日期:2019-09-15点击:347

先看题面:

随机生成一个长度为 10 的整数类型的数组,例如 [2, 10, 3, 4, 5, 11, 10, 11, 20],将其排列成一个新数组,要求新数组形式如下,例如 [[2, 3, 4, 5], [10, 11], [20]]。

看完有点懵,根据他举的例子,数组被分为了三个子数组,但分类的依据却有两种理解,1.按照区间划分,即0-9,10-19,20-29等等,依此类推,以10为阶梯进行分组。2.按照连续区间划分,大小连续的分为一组。

嗯,到底出题人咋想的,不得而知。so 管他呢,写就完了

我们先按照第一种理解:

 // IIFE 生成随机数组 var arr = (function (len) { let temp = [] for (var i = 0; i < len; i++) { temp.push(Math.floor(Math.random() * 100)); } return temp; })(10) console.log(arr); //1.排序 重写sort 排序 arr.sort((a, b) => { return a - b }) console.log(arr); //2去重 利用set不可重复性对数组进行去重 arr = [...new Set(arr)] console.log(arr); //3.区间分组 利用map的key记录阶梯索引 let map = new Map(); arr.forEach((item) => { let key = Math.floor(item / 10) let temp=map[key]; if(!temp) { temp=[]; } temp.push(item); map[key]=temp; }) let arr1=[] for(var key in map) { arr1.push(map[key]); } console.log(arr1);

如果是连续区间其实也可以利用我们已经排序的优势来实现。

 //4.连续分组 利用map的key记录分组索引 let map2 = new Map(); let index = 0 arr.forEach((item) => { let temp = map2[index]; if (!temp) { temp = []; temp.push(item); } else { if (item - temp[temp.length - 1] == 1) { temp.push(item); } else { index++; temp = [] temp.push(item); } } map2[index] = temp; }) let arr2 = [] for (var key in map2) { arr2.push(map2[key]); } console.log(arr2);

最终效果如图
0916

以上写法使用的算法都比较传统,有网友提出用reduce函数进行处理,等我学会了再来写一稿。

原文链接:https://yq.aliyun.com/articles/718486
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章