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

 1 /**
 2     * 一个产生10个长度随机整数数组的函数
 3     */
 4 function getRandomInt() {
 5     let arr = [];
 6     for (let index = 0; index < 10; index++) {
 7         arr.push(Math.round(Math.random() * 50));
 8     }
 9     return arr;
10 }
11 
12 let arr = getRandomInt();
13 /**
14     * 数组去重  排序
15     */
16 arr = Array.from(new Set(arr)).sort((a, b) => {
17     return a - b;
18 });
19 
20 /**
21     * 0-9一组
22     * 10-19一组 类推
23     */
24 var result = [];
25 arr.forEach(function (val) {
26     let index = parseInt(val / 10);
27     if (!result[index]) {
28         result[index] = [];
29     }
30     result[index].push(val);
31 })
32 
33 console.log(result);

猜你喜欢

转载自www.cnblogs.com/ljl-zszy/p/11763952.html