Fork me on GitHub

常见JavaScript算法题的ES6实现

统计一个字符串出现频率最高的字母/数字

let str = 'asdfghjklaqwertyuiopiaia'
const strChar = str => {
let string = [...str]
let maxValue = ''
let obj = {}
let max = 0
string.forEach(value => {
obj[value] = obj[value] == undefined ? 1 : obj[value] + 1
if (obj[value] > max) {
max = obj[value]
maxValue = value
}
})
return maxValue
}
console.log(strChar(str)) // a

数组去重

  • forEach

    let arr = ['1', '2', '3', '1', 'a', 'b', 'b']
    const unique = arr => {
    let obj = {}
    arr.forEach(value => {
    obj[value] = 0
    })
    return Object.keys(obj)
    }
    console.log(unique(arr)) // ['1','2','3','a','b']
  • filter

    let arr = ['1', '2', '3', '1', 'a', 'b', 'b']
    const unique = arr => {
    return arr.filter((ele, index, array) => {
    return index === array.indexOf(ele)
    })
    }
    console.log(unique(arr)) // ['1','2','3','a','b']
  • set

    let arr = ['1', '2', '3', '1', 'a', 'b', 'b']
    const unique = arr => {
    return [...new Set(arr)]
    }
    console.log(unique(arr)) // ['1','2','3','a','b']

翻转字符串

let str ="Hello Dog"
const reverseString = str =>{
return [...str].reverse().join("")
}
console.log(reverseString(str)) // goD olleH

数组中最大差值

  • forEach

    let arr = [23, 4, 5, 2, 4, 5, 6, 6, 71, -3]
    const difference = arr => {
    let min = arr[0]
    let max = 0
    arr.forEach(value => {
    if (value < min) min = value
    if (value > max) max = value
    })
    return max - min
    }
    console.log(difference(arr)) // 74
  • max、min

    let arr = [23, 4, 5, 2, 4, 5, 6, 6, 71, -3]
    const difference = arr => {
    let max = Math.max(...arr)
    let min = Math.min(...arr)
    return max - min
    }
    console.log(difference(arr)) // 74

不借助临时变量,进行两个整数的交换

  • 数组解构

    let a = 2
    let b = 3
    [b, a] = [a, b]
    console.log(a, b) // 3 2
  • 算术运算(加减)

    let a = 2
    let b = 3
    const swop = (a, b) => {
    b = b - a
    a = a + b
    b = a - b
    return [a,b]
    }
    console.log(swop(2, 3)) // [3,2]
  • 逻辑运算(异或)

    let a = 2
    let b = 3
    const swop = (a, b) => {
    a ^= b //x先存x和y两者的信息
    b ^= a //保持x不变,利用x异或反转y的原始值使其等于x的原始值
    a ^= b //保持y不变,利用x异或反转y的原始值使其等于y的原始值
    return [a,b]
    }
    console.log(swop(2, 3)) // [3,2]