大家可能对递归算法并不陌生,但是在我们实战项目中遇到需要使用递归算法的时候不知道如何下手。下面是我个人总结出来的经验,如果有不对的地方欢迎大家指正。
递归算法使用步骤:
第一步
分析目标数据规律:大多数记录的pid都对应了某记录的ID
第二步
分析预期结果:预期结果是否可以通过分析出来的规则直接或间接实现
第三步
确定每次递归的参数和递归终止条件
下面我以常见的多级分类(js树形结构)为例:
1 const _ = require('lodash') 2 let a = [{ 3 id: 1, 4 pid: 0 5 }, { 6 id: 2, 7 pid: 1 8 }, { 9 id: 3, 10 pid: 2 11 }, { 12 id: 4, 13 pid: 1 14 }, { 15 id: 5, 16 pid: 2 17 }, { 18 id: 6, 19 pid: 4 20 }] 21 /** 22 * 递归使用: 23 * 前提:是否有规律 24 * 第一步分析目标数据规律: 25 * 规律:大多数记录的pid都对应了某记录的ID 26 * 第二步分析预期结果: 27 * 预期结果:{id:xx,pid:xx,children:[{id:xx,pid:x, ...},...]} 28 * 预期结果是否可以通过分析出来的规则直接或间接实现 29 * 第三步确定每次递归的参数和递归终止条件 30 */ 31 let aHandle = _.groupBy(a, 'pid') // 运行结果:{"0":[{"id":1,"pid":0}],"1":[{"id":2,"pid":1},{"id":4,"pid":1}],"2":[{"id":3,"pid":2},{"id":5,"pid":2}],"4":[{"id":6,"pid":4}]}
32 let b = formatTree(aHandle, '0', 'id') 33 console.log(JSON.stringify(b)) 34 35 function formatTree(items, parentId, cKey) { 36 let result: any[] = [] 37 if (!items[parentId]) { 38 return result 39 } 40 for (let t of items[parentId]) { 41 const temp = formatTree(items, t[cKey], cKey) 42 if (temp.length > 0) { 43 t.children = temp 44 } 45 result.push(t) 46 } 47 return result 48 }
运行结果如下:
1 [ 2 { 3 "id":1, 4 "pid":0, 5 "children":[ 6 { 7 "id":2, 8 "pid":1, 9 "children":[ 10 { 11 "id":3, 12 "pid":2 13 }, 14 { 15 "id":5, 16 "pid":2 17 } 18 ] 19 }, 20 { 21 "id":4, 22 "pid":1, 23 "children":[ 24 { 25 "id":6, 26 "pid":4 27 } 28 ] 29 } 30 ] 31 } 32 ]