关于递归,算法当中基础中的基础,掌握不好,一切算法都是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的,都是先写逻辑,再写递归函数