数组的方法

reduce方法

 1 // 累加
 2         const result = [1, 2, 3].reduce((pre, cur) => pre + cur);
 3 
 4         // 找最大值
 5         const result = [1, 2, 3, 2, 1].reduce((pre, cur) => Math.max(pre, cur))
 6 
 7         // 数组去重
 8         const resultList = [1, 2, 3, 2, 1].reduce((preList, cur) => {
 9 
10             if (preList.indexOf(cur) === -1) {
11 
12                 preList.push(cur)
13 
14             }
15 
16             return preList
17 
18         }, [])
19 
20         // 归类
21         const dataList = [
22             {
23                 name: "aa",
24                 country: "China"
25             },
26             {
27                 name: "bb",
28                 country: "China"
29             },
30             {
31                 name: "cc",
32                 country: "USA"
33 
34             },
35             {
36                 name: "dd",
37                 country: "En"
38             }
39         ]
40 
41         const reslutObj = dataList.reduce((preObj, cur) => {
42             const { country } = cur;
43             if (!preObj[country]) {
44 
45                 preObj[country] = [];
46 
47             }
48             preObj[country].push(cur);
49             return preObj;
50         }, {});
51 
52         // 字符串的反转
53         const str = "hello world";
54         const reslutStr = Array.from(str).reduce((pre, cur) => {
55             return `${cur}${pre}`;
56         }, '');

 

posted @ 2023-06-15 08:11  lisa2544  阅读(8)  评论(0编辑  收藏  举报