// es6 :reduce
reduce() 方法接受两个参数:第一个参数是一个回调函数,第二个参数是初始值。回调函数又接受两个参数:累加器和当前元素。 【这个函数将数组中的所有元素迭代处理,并将结果累加到一个单一的值中】
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // 输出:15
//数组扁平化 递归数字扁平化
const falttten = arr => arr.reduce(acc, val)=>acc.concat(Array.isArray(val)? flatten(val: val), [])
//项目实例 一
const tempAdqtDictList = treeDataChildrenClear(res.data);
const { specialTask, otherDictList } = tempAdqtDictList.reduce(
({ specialTask, otherDictList }, item) => {
if (item.dictLabel.includes('专项')) {
specialTask.push(item);
} else {
otherDictList.push(item);
}
return { specialTask, otherDictList };
},
{ specialTask: [], otherDictList: [] }
);
this.specialTask = specialTask;
this.labelDictList = otherDictList;
//项目实例 二
getUserTypeTreeList('01').then((res) => {
const tempRelatedLabelList = treeDataChildrenClear(res.data);
const idMap = {
'28422402656436225': 'longTimeList',
'28422402656436232': 'longTimeList',
'28422402656436233': 'longTimeList',
'2024082528': 'longTimeList',
'28422402656436231': 'shortTimeList',
'28422402656436230': 'shortTimeList',
'28422402656436227': 'shortTimeList'
};
const labeledLists = tempRelatedLabelList.reduce((acc, item) => {
if (idMap[item.id]) {
acc[idMap[item.id]].push(item);
}
return acc;
}, { longTimeList: [], shortTimeList: [] });
this.longTimeList = labeledLists.longTimeList;
this.shortTimeList = labeledLists.shortTimeList;
});