vue双端算法代码分析、数组转树(tree)结构

let oldArray = [1, 2, 3, 4, 5];
let newArray = [1, 2, 6, 4, 5];

function patch(oldArr, newArr) {
  let oldStart = 0;
  let oldEnd = oldArr.length - 1;
  let newStart = 0;
  let newEnd = newArr.length - 1;
  // 对比双数组循环的好处是循环减少了,用时减少了
  while (oldStart <= oldEnd && newStart <= newEnd) {
    if (oldArr[oldStart] === newArr[newStart]) { // 比较前面
      oldStart++;
      newStart++;
    } else if (oldArr[oldEnd] === newArr[newEnd]) { // 比较后面
      oldEnd--;
      newEnd--;
    } else if (oldArr[oldStart] === newArr[newEnd]) { // 比较前面后面
      oldStart++;
      newEnd--;
    } else if (oldArr[oldEnd] === newArr[newStart]) { // 比较前面后面
      oldEnd--;
      newStart++;
    } else {
      // 插入新元素到 oldArr
      oldArr.splice(oldStart, 0, newArr[newStart]);
      oldStart++;
      oldEnd++;
      newStart++;
    }
  }
  // 删除多余的元素
  while (oldStart <= oldEnd) {
    oldArr.splice(oldStart, 1);
    oldEnd--;
  }
  while (newStart <= newEnd) {
    oldArr.splice(oldStart, 0, newArr[newStart]);
    oldStart++;
    newStart++;
  }
}
patch(oldArray, newArray)
// console.log(oldArray); // [1, 2, 6, 4, 5]
const flatArr = [
  { id: '01', parentId: 0, name: '节点1' },
  { id: '011', parentId: '01', name: '节点1-1' },
  { id: '0111', parentId: '011', name: '节点1-1-1' },
  { id: '02', parentId: 0, name: '节点2' },
  { id: '022', parentId: '02', name: '节点2-2' },
  { id: '023', parentId: '02', name: '节点2-3' },
  { id: '0222', parentId: '022', name: '节点2-2-2' },
  { id: '03', parentId: 0, name: '节点3' },
]
// 转成树形结构
function getData (arr) {
  // 利用两层filter实现
  let data = arr.filter(item => {
    // 循环改变原数组里的东西
    item.children = arr.filter(e => {
      if(item.id === e.parentId) {
        console.log(item);
      }
      return item.id === e.parentId
    })
    return !item.parentId
  })

  return data
}
const arrData = getData(flatArr)
console.log('arrData', arrData)

 

posted @ 2023-10-18 11:32  王小美丶  阅读(50)  评论(0编辑  收藏  举报