let result =[{"id":1,"name":"1级1","parentId":0,"children":[{"id":4,"name":"1级1-1","parentId":1,"children":[{"id":6,"name":"1级1-1-1","parentId":4,"children":[{"id":15,"name":"1级1-1-1-1","parentId":6,"children":[]}]}]}]},{"id":13,"name":"3级1","parentId":0,"children":[{"id":14,"name":"3级1-1","parentId":13,"children":[]}]},{"id":2,"name":"2级1","parentId":0,"children":[{"id":12,"name":"2级1-1","parentId":2,"children":[]}]}]//树形数据转换编平数据let list = result.reduce(function(pre,cur){
console.log(cur);
pre.push({id:cur.id,name:cur.name,parentId:cur.parentId
})
cur.children && cur.children.forEach(el=>{//多用于递归调用,对于没有函数名的匿名函数也非常起作用
arguments.callee(pre,el)});return pre
},[])
console.log(list);
扁平数据转换树形数据
const temp =[{'id':1,'name':'1级1','parentId':0},{'id':13,'name':'3级1','parentId':0},{'id':4,'name':'1级1-1','parentId':1},{'id':6,'name':'1级1-1-1','parentId':4},{'id':12,'name':'2级1-1','parentId':2},{'id':14,'name':'3级1-1','parentId':13},{'id':15,'name':'1级1-1-1-1','parentId':6},{'id':2,'name':'2级1','parentId':0},]const result = temp.reduce(function(prev, curr, i, arr){
curr.children = arr.filter(v=> v.parentId === curr.id)if(curr.parentId ==0){
prev.push(curr)}return prev
},[])
数组去重
//数组去重let arr2 =[1,1,1,12,2,4,5,5,6,7,8]let sun = arr2.reduce((pre,cur)=>{if(!pre.includes(cur)){return pre.concat(cur)}else{return pre
}},[])
console.log(sun);
统计字符出现次数,输出最多的字符和次数
let cuelist ='sdfesrfjselfjaiosadjfsafdwsfjsdiorjffsdjfsdjhtioghjerjfgsdjfsdf'let yum = cuelist.split('').reduce((pre,cur)=>{if(cur in pre){
pre[cur]++}else{
pre[cur]=1}return pre
},{})
console.log(yum);
多维数组转换一维数组
let arr1 =[[1,2],[1,[11,23,[1,1,[2,[1]]]]]]letnewArr1=function(arr){return arr.reduce((pre, cur)=> pre.concat(Array.isArray(cur)?newArr1(cur): cur),[])}
对象里的属性求和
var result =[{subject:'math',score:10},{subject:'chinese',score:20},{subject:'english',score:30}];var sum = result.reduce(function(prev, cur){return cur.score + prev;},0);
console.log(sum)//60