js中数组迭代归并方法的原理及实现

JavaScript025

js中数组迭代归并方法的原理及实现,第1张

数组的迭代方法,每个方法都会接受两个参数:(1)要在每一项上运行的函数(2)运行该函数的作用域——影响this的值(可选)。传入方法中的函数会接受三个参数:(1)数组每项的值(2)该项在数组中的位置(3)数组对象本身。

5种迭代方法的作用如下:

数组还有两个归并的方法:reduce和reduceRight。这两个方法会迭代数组的所有项,最终返回一个迭代的最后值。reduce方法从数组的第一项开始迭代,reduceRight则从数组的最后一项开始。两个方法接受参数相同,都是两个参数:一个是在在每项上调用的函数以及迭代的初始值(可选)。下面,我们对reduce方法的实现进行详解。

ES6规范中Set数据结构,类似于数组,但其中的值全都是唯一的。搭配数组的迭代方法,我们能够快速方便地实现两个或多个数组的交、并、差集。

MDN web docs

ECMAScript 6入门

1、方法思路使用js数组自带的filter()方法;数据格式要求,父子节点通过,Id,ParentId进行关联。默认父结节id为0。

样例数据:var jsonData = [{"id":"1","pid":"0","name":"家用电器"}, {"id":"4","pid":"1","name":"大家电"}, {"id":"5","pid":"1","name":"生活电器"}, {"id":"2","pid":"0","name":"服饰"}, {"id":"3","pid":"0","name":"化妆"}, {"id":"7","pid":"4","name":"空调"}, {"id":"8","pid":"4","name":"冰箱"}, {"id":"9","pid":"4","name":"洗衣机"}, {"id":"10","pid":"4","name":"热水器"}, {"id":"11","pid":"3","name":"面部护理"}, {"id":"12","pid":"3","name":"口腔护理"}, {"id":"13","pid":"2","name":"男装"}, {"id":"14","pid":"2","name":"女装"}, {"id":"15","pid":"7","name":"海尔空调"}, {"id":"16","pid":"7","name":"美的空调"}, {"id":"19","pid":"5","name":"加湿器"}, {"id":"20","pid":"5","name":"电熨斗"}]

2、实现方法:

function creatTreeData(list){

var clonelist = JSON.parse(JSON.stringify(list))

var result =clonelist.filter(function(father){

var childlist = clonelist.filter(function(child){

return father.id= child.pid

})

if(childlist.length>0){

father.children=childlist

}

return father.pid ==0

})

return result

}

3、方法封装

function treeData(list,id,pid,children){

var clone = JSON.parse(JSON.stringify(list))

return clone.filter(function(father){

var childlist =clone.filter(function(child){

return father[id]==child[pid]

})

if(childlist.length>0){

father[children]=childlist

}

return father[pid]==0

})

}