前端常用JS代码片段 - 数组操作
日常积累了一些常用JS片段,在此做个总结记录。
# 数组转树
/**
* list转树
* @param list 对象数组
* @param idKey
* @param pidKey
*/
export const list2Tree = (list: any[], idKey = 'id', pidKey = 'pid') => {
list.forEach(f => {
f.children = list.filter(g => {
if (g[pidKey] === f[idKey]) {
g._parentId = g[pidKey];
return true;
}
return false;
});
});
return list.filter(item => !item._parentId);
};
# 另一种方法-时间复杂度O(n)
/**
* list转树
* @param list 对象数组
* @param idKey
* @param pidKey
*/
export const listToTree = (list: any[], idKey = 'id', pidKey = 'pid') => {
const res = [];
const map = list.reduce((res, v) => (res[v[idKey]] = v, res), {});// 存入map,方便获取
for (const item of list) {
if (!item[pidKey]) { // 根节点
res.push(item);
continue;
}
if (item[pidKey] in map) {
const parent = map[item[pidKey]];
parent.children = parent.children || [];
parent.children.push(item);
}
}
return res;
};
// 更简洁
export const listToTree = (list: any[]) => {
const info = list.reduce((map, node) => (map[node.id] = node, node.children = [], map), {});
return list.filter((node) => {
info[node.parentId] && info[node.parentId].children.push(node);
return !node.parentId;
});
};
# 树转数组
// 深度优先
export const tree2List = (tree,list = []) => {
tree.forEach((node) => {
list.push(node); // 先序遍历
node.children && tree2List(node.children,list); // 遍历子树
// list.push(node); // 后序遍历
});
return list
};
# 带层级
export const tree2ListWithLv = (tree,list = [],lv=0) => {
tree.forEach((node) => {
list.push(node); // 先序遍历
node.lv=lv+1
node.children && tree2ListWithLv(node.children,list,lv+1); // 遍历子树
// list.push(node); // 后序遍历
});
return list
};
# 数组去重复
/**
* 简单数组去重复
* @param arr
*/
export const deduplication = (arr: string|number[]) => {
return [...new Set(arr)];
}
# 对象数组去重复
/**
* 对象数组去重复
* @param arr 数组
* @param key 去重复依据key
*/
export const unique = (arr:object[], key:string) => {
const hash = {};
return arr.reduce((item, next) => {
if (!hash[next[key]]) {
hash[next[key]] = true;
item.push(next);
}
return item;
}, []);
};
# 数组交集
export const intersection = (arr1,arr2)=>{
return arr1.filter(v => arr2.includes(v))
}
# 数组并集
export const diff = (arr1,arr2)=>{
return [...new Set([...arr1,...arr2])]
}
# 数组差集
export const diff = (arr1,arr2)=>{
return arr1.filter(v => !arr2.includes(v))
}
# 数组乱序
export const shuffle = (arr:any[])=> {
let array = arr
let index = array.length
while (index) {
index -= 1
let random = Math.floor(Math.random() * index)
let temp = array[index]
array[index] = array[random]
array[random] = temp
}
return array
}
// 另一种方法
export const shuffle2 = (arr:any[])=> {
return arr.sort(()=>Math.random()-0.5)
}