[toc]
数组相关
一维数组和二维数组相互转换
/* 一维数组转二位数组 */
function oneDimensionalToTwo(array, length) {
if(!array.length || !length || array.length < length) return array
const newArr = []
let j = -1
for (let i = 0; i < array.length; i++) {
if(i%length === 0) {
j++
newArr[j] = []
}
newArr[j].push(array[i])
}
return newArr
}
/* 一维数组转二位数组 */
// 参考 js 笔记中的 flat 方法
判断数组内容是否相同
当前只针对简单的基础类型数组值判断
function equalArray (arr1, arr2) {
if(!(arr1 instanceof Array) || !(arr2 instanceof Array)) return false
if (arr1.length !== arr2.length) return false
for (let i = 0; i < arr1.length; i++) {
if(!arr2.includes(arr1[i])) return false
}
return true
}
function equalObjectArray(arr1, arr2) {
if (!(arr1 instanceof Array) || !(arr2 instanceof Array)) return false
if (arr1.length !== arr2.length) return false
for (let i = 0; i < arr1.length; i++) {
/* equalObject 在 object.md */
if (!arr2.some(item => equalObject(item, arr1[i]))) {
return false
}
}
return true
}
数组的交集
/**
* @des 获取数组的交集
*/
export const arrayIntersection = (r1, r2) => {
const a = [...new Set(r1)]
const b = [...new Set(r2)]
return a.filter(v => b.includes(v))
}
遍历树
const tree = [
{
id: 1,
label: '一级 1',
children: [{
id: 4,
label: '二级 1-1',
children: [{
id: 9,
label: '三级 1-1-1'
}, {
id: 10,
label: '三级 1-1-2'
}]
}]
}, {
id: 2,
label: '一级 2',
children: [{
id: 5,
label: '二级 2-1'
}, {
id: 6,
label: '二级 2-2'
}]
}, {
id: 3,
label: '一级 3',
children: [{
id: 7,
label: '二级 3-1'
}, {
id: 8,
label: '二级 3-2'
}]
}]
const loopTree = (data, level) => {
const tempArr = [];
data.forEach(v => {
const tempObj = {}
tempObj.id = v.id
tempObj.label = `new ${v.label}-level:${level}`
if (v.children && v.children.length) {
tempObj.list = loopTree(v.children, level+1)
}
tempArr.push(tempObj)
})
return tempArr
}
console.log(loopTree(tree, 0));