对于递归,算法当中根底中的根底,把握不好,所有算法都是 0.
以下是几个递归,在了解当中记忆,记录它们重在了解,不在记忆。
1、多维数组打成 map 映射。
const buildMapDataSource = (
dataSource,
target = {},
level = 1,
parentKey = null,
) => {for (let i = 0; i < dataSource.length; i++) {const item = dataSource[i];
let key = !parentKey ? `${i}` : `${parentKey}-${i}`;
if (!target[item.id]) {target[item.id] = item;
item.level = level;
item.key = key;
}
if (Array.isArray(item?.children)) {buildMapDataSource(item.children, target, level + 1, key);
}
}
return target;
};
2、多维数组,每项打入 key,示意层级,相似 key=’0-0-0-1′.
const buildStandardArr = (data, parentId = null) => {const result = [];
data.forEach((item, index) => {if (item.parentId === parentId) {const key = parentId !== null ? `${parentId}-${index}` : `${index}`;
const newItem = {...item, key};
const children = buildStandardArr(data, item.id);
if (Array.isArray(children) && children.length) {newItem.children = children;}
result.push(newItem);
}
});
return result;
}
3、把一维打成 tree 多维,集体感觉这个比拟难了解;
const buildMultipleArr = (data, parentId = null) => {const result = [];
data.forEach(item => {if (item.parentId === parentId) {const children = buildMultipleArr(data, item.id);
const newItem = {...item};
if (Array.isArray(children) && children.length) {newItem.children = children;}
result.push(newItem);
}
});
return result;
};
4、通过 parentId 获取 parent
const getParent = (data, parentId = null, parent = null) => {for (let i = 0; i < data.length; i++) {const item = data[i];
if (item.parentId === parentId) {return parent;}
if (Array.isArray(item?.children) && item.children.length) {const parent = getParent(item.children, parentId, item);
if (parent) {return parent;}
}
}
return null;
}
5、对多维数组,外部的节点排序
const sortNodes = (data) => {data.sort((a, b) => a.sort - b.sort)
data.forEach(item => {if (Array.isArray(item?.children) && item.children.length) {sortNodes(item.children);
}
});
return data;
}
6、获取多维数组,某一项 Item 外部(有多层 children 嵌套)最大的层级
const getMaxLevel = (obj) => {
let maxLevel = 0;
function traverse(node, level) {if (level > maxLevel) {maxLevel = level;}
if (Array.isArray(node.children)) {
node.children.forEach(child => {traverse(child, child.level);
});
}
}
traverse(obj, obj.level);
return maxLevel;
}
从下面的例子来看
须要数组 push 的,都是先写递归函数,再写 push 追加的内容
须要返回一个 object 的,都是先写逻辑,再写递归函数