算法题记录

1、将对象数组中名称相同的对象选项组成新的对象数组。
eg:

原始数组:originalArr = [
	{ name: '张三', age: 13 },
	{ name: '李四', age: 14},
	{ name: '张三', age: 15 },
	{ name: '王五', age: 16 },
	{ name: '王五', age: 17},
]
结果数组:
[
	{ name: '张三', age: 13 },
	{ name: '张三', age: 15 },
	{ name: '王五', age: 16 },
	{ name: '王五', age: 17},
]

实现方式:

  let originalArr = [
    {name: '张三', age: 13},
    {name: '李四', age: 14},
    {name: '张三', age: 15},
    {name: '王五', age: 16},
    {name: '王五', age: 17},
  ]
  let tempObj = {}
  let resultArr = []
  originalArr.forEach(item => {
    if (Object.keys(tempObj).indexOf(item.name) === -1) {
      tempObj[item.name] = []
    }
    tempObj[item.name].push(item)
  })
  Object.keys(tempObj).forEach(item => {
    if (tempObj[item].length > 1) {
      resultArr = [...resultArr, ...tempObj[item]]
    }
  })
  console.log(resultArr)

打印结果:
算法题记录_第1张图片
2、打印1-10000对称的数,如11、33、121

    for(let i =1; i < 10000; i++) {
      let tempArr = i.toString().split('')
      let flag = true
      tempArr.forEach( ( item, idx ) => {
        let tempIdx = -(idx+1)
        if ( i <= 10 || item !== tempArr.at(tempIdx) && flag) {
          console.log('进来了')
          flag = false
        }
      })
      if ( flag ) {
        console.log(i)
      }
    }

3、用递归算法实现,数组长度为5且元素的随机数在2-32间不重复的值

	function tempFunc(tempArr = [], randomMin = 2, randomMax = 32, arrLength = 5) {
	  const resultArr = tempArr
	  const randomNum = randomMin + Math.floor(Math.random() * (randomMax - randomMin))
	  if (!resultArr.includes(randomNum)) {
	    resultArr.push(randomNum)
	  }
	  if (resultArr.length === arrLength) {
	    console.log('resultArr', resultArr)
	    return
	  }
	  tempFunc(resultArr)
	}
	
	tempFunc()

你可能感兴趣的:(JS,vue.js,前端,javascript)