老孟的前端算法题积累

1、对数组中对象的某一属性进行排序

 let arr = [
    {
      name: 'ad',
      age: 20
    },
    {
      name: 'james',
      age: 38
    },
    {
      name: 'rose',
      age: 27
    },
    {
      name: 'curry',
      age: 30
    }
  ]

  function compare (property) {
    return function (a, b) {
      let val1 = a[property]
      let val2 = b[property]
      return val1 - val2
    }
  }

  console.log(arr.sort(compare('age')))

2、连字符串改为驼峰

将  get-element-by-id  转为  getElementById

 // get-element-by-id 转为 getElementById

// 思路:
// 1.先用split方法将字符串转成分割开的字符串组成的数组
// 2.利用for循环(注意从 i=1 开始,第一个不需要大写)和charAt()toUpperCase()方法将每个字符串的第一个元素获取到并且转成大写
// 3.再使用substring()方法将截取第一个元素后与转成大写死一个元素进行一个拼接,最终利用join()转回成字符串

  let str = 'get-element-by-id'
  let arr = str.split('-')

  for (let i = 1; i < arr.length; i++) {
    arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].substring(1)
  }

  console.log(arr.join(''))   // getElementById


//  ----------charAt()   返回指定位置的字符  可以理解成字符串的下标 
//  例如:
//  let str = 'abcd'
//  str.charAt(0)  => a  
//  str.charAt(2)  => c  


//  ----------toUpperCase()   让字符从小写转为大写
//  ----------toLowerCase()   让字符从大写转为小写
//  例如:
//  let str = 'abcd'
//  str.toUpperCase()  => ABCD
//  str.charAt(2).toUpperCase()  => C


//  ----------substring()    截取字符串:从头截取,返回后边剩下的
//  例如:
//  let str = 'abcd'
//  str.substring(0)  => abcd  截取0个,返回剩下的4个
//  str.substring(2)  => cd    截取2个,返回剩下的后2个

3、按要求输出字符串

输入 'a(12)b(2)cde(1)f(0)';
输出 "aaaaaaaaaaaabbcde"

  function generateString (str) {
    let result = ''
    const regex = /([a-z]+)\((\d+)\)/g  // 匹配a(12)、b(2)...
    let match
    while ((match = regex.exec(str)) !== null) {
      const [_, char, count] = match
      result += char.repeat(parseInt(count))
    }
    return result
  }

console.log(generateString('a(12)b(2)cde(1)f(0)'))

4、取某个区间的整数

Math.floor(Math.random() * (max - min + 1)) + min

5、平面数据结构和树形数据结构

// 1. 遍历原数组 以数组中的每一项的id作为key 每一项本身作为value形成一个对象map [方便查找]

// 2. 遍历原数组 通过pid去匹配id 如果匹配上了 就把当前项添加到匹配项的chilren属性中


function transTree(arr) {
  const treeList = []
  const map = {}
  arr.forEach(item => {
    map[item.id] = item
    // 初始化一个空的children数组出来
    map[item.id].children = []
  })
  arr.forEach(item => {
    if (map[item.pid]) {
      // 匹配到了
      map[item.pid].children.push(item)
    } else {
      // 没有发生匹配
      treeList.push(item)
    }
  })
  return treeList
}

export default transTree
  // 1、调用后台接口拿到数据,我们在这里自己定义数据
  const data = [
    { id: 1, name: "集团", parentId: 0 },
    { id: 2, name: "开发部", parentId: 1 },
    { id: 3, name: "人事部", parentId: 1 },
    { id: 4, name: "财务部", parentId: 1 },
    { id: 5, name: "研发4", parentId: 2 },
    { id: 6, name: "财务1", parentId: 4 },
    { id: 7, name: "开发-研发4-前端老孟", parentId: 5 },
    { id: 8, name: "财务-财务1-出纳", parentId: 6 },
  ]
  // 2、封装平铺数组转成树形结构数组方法,就是利用parentId去匹配id的一个过程
  function buildTree (data, parentId) {
    const tree = []
    for (let i = 0; i < data.length; i++) {
      if (data[i].parentId === parentId) {
        const treeNode = {
          id: data[i].id,
          name: data[i].name,
          children: buildTree(data, data[i].id),
        }
        tree.push(treeNode)
      }
    }
    return tree
  }

  const treeData = buildTree(data, 0)
  console.log(treeData)

  // 3、我们可以将树形结构的数据绑定到自定义的树形组件上进行展示
  function TreeNode ({ node }) {
    return (
      <div>
        {node.name}
        {node.children && node.children.map((child) => (
          <TreeNode key={child.id} node={child} />
        ))}
      </div>
    )
  }
  function Tree ({ data }) {
    return (
      <div>
        {data.map((node) => (
          <TreeNode key={node.id} node={node} />
        ))}
      </div>
    )
  }

  ReactDOM.render(<Tree data={treeData} />, document.getElementById("root"));

6、删除子节点


function deleteNode (typeNum, nodeName) {
  const nodes = document.querySelectorAll(`${nodeName}`)
  for (let i = 0; i < nodes.length; i++) {
    if (i % 2 === typeNum) {
      nodes[i].parentNode.removeChild(nodes[i])
    }
  }
}

// typeNum: 
// 0 保留偶数子项 ;  
// 1 保留奇数子项

// nodeName:
// 被删除的节点: 
// 类名:.name;
// id: #name;
// 标签:标签名

7、克隆

// 使用既有方法实现对象克隆可以使用Object.assign()或扩展运算符...。例如:
  // const obj1 = { name: 'Alice', age: 25 }
  // const obj2 = Object.assign({}, obj1)
  // // 或者
  // const obj3 = { ...obj1 }

  // 自定义通用方法实现深克隆可以使用递归来遍历对象的所有属性,并创建一个新的对象。以下是一个使用JavaScript基础代码实现深克隆的示例:
  function deepClone (obj) {
    if (obj === null || typeof obj !== 'object') {
      return obj
    }
    let clone = Array.isArray(obj) ? [] : {}
    for (let key in obj) {
      if (obj.hasOwnProperty(key)) {
        clone[key] = deepClone(obj[key])
      }
    }
    return clone
  }

  // 下面是一个具体数据的示例,用于比较深克隆和浅克隆的效果:
  const obj1 = {
    name: 'rose',
    age: 18,
    hobbies: ['basketball', 'football']
  }

  const obj2 = { ...obj1 }
  const obj3 = deepClone(obj1)

  obj2.name = 'anthony'
  obj2.hobbies.push('playing')

  obj3.name = 'james'
  obj3.hobbies.push('table')

  console.log(obj1)  //  ['basketball', 'football', 'playing']
  console.log(obj2)  //  ['basketball', 'football', 'playing']
  console.log(obj3)  //  ['basketball', 'football', 'table']

8、求两个一维数组的交集


  //  求两个一维数组的交集
  // 方法1
  let arr1 = [1, 2, 3, 4, 5]
  let arr2 = [2, 3, 5, 7, 9]
  let totalArr = []

  for (let i = 0; i < arr1.length; i++) {
    if (arr2.indexOf(arr1[i]) !== -1) {
      totalArr.push(arr1[i])
    }
  }
  console.log(totalArr)


  // 方法2
  const arr1 = [1, 2, 3, 4, 5]
  const arr2 = [3, 4, 5, 6, 7]
  function totalArr (arr1, arr2) {
    const set1 = new Set(arr1)
    const set2 = new Set(arr2)
    const intersection = [...set1].filter(x => set2.has(x))
    return intersection
  }

  console.log(totalArr(arr1, arr2)) // [3, 4, 5]

9、给定一个数组arr和一个目标值target,从arr中找到两个数相加等于target,并返回它们的下标

// 这是数组中只存在一组数据满足要求
function findTwoSum (arr, target) {
    for (let i = 0; i < arr.length; i++) {
      for (let j = 0; j < arr.length; j++) {
        if (arr[i] + arr[j] === target) {
          return [i, j]
        }
        j++
      }
    }
    return null
  }

  console.log(findTwoSum(arr, target))

// 多组数据满足要求,皆可查询出来
  function findTwoSum (arr, target) {
    const result = []
    for (let i = 0; i < arr.length; i++) {
      for (let j = 0; j < arr.length; j++) {
        if (arr[i] + arr[j] === target) {
          result.push([i, j])
        }
        j++
      }
    }
    return result
  }

  console.log(findTwoSum(arr, target))
  // 一组数据满足要求
  function findTwoSum (arr, target) {
    const map = new Map()
    for (let i = 0; i < arr.length; i++) {
      const complement = target - arr[i]
      if (map.has(complement)) {
        return [map.get(complement), i]
      }
      map.set(arr[i], i)
    }
    return null
  }

  console.log(findTwoSum(arr, target));

  // 多组数据满足要求
  function findTwoSum (arr, target) {
    const result = []
    for (let i = 0; i < arr.length; i++) {
      const complement = target - arr[i]
      if (arr.includes(complement)) {
        result.push([arr.indexOf(complement), i])
      }
    }
    return result
  }

  console.log(findTwoSum(arr, target))

  // 多组数据满足要求
  function findTwoSum (arr, target) {
    const map = new Map()
    const result = []
    for (let i = 0; i < arr.length; i++) {
      const complement = target - arr[i]
      if (map.has(complement)) {
        result.push([map.get(complement), i])
      }
      map.set(arr[i], i)
    }
    return result
  }

  console.log(findTwoSum(arr, target));

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值