1、js 统计一个字符串出现频率最高的字母/数字
let str = 'absafdaf234234323232' let a = [...str] // alert(a instanceof Array) const strChar = str => { let strArr = [...str] maxValue='', maxKey = '' obj = {} strArr.forEach(val =>{ obj[val] = obj.hasOwnProperty(val) ? obj[val]+1 : 1 if(obj[val] > maxValue){ maxValue = obj[val] maxKey = val } }) return { key: maxKey, value: maxValue } } console.log(strChar(str)) // {key: 3, value: 5}
2、数组去重
forEach
let arr = ['1', '2', '3', '1', 'a', 'b', 'b'] const unique = arr => { let obj = {} arr.forEach(value => {
// 对象key值是唯一, 使用 Object.keys 转为数组形式 obj[value] = 0 }) return Object.keys(obj) } console.log(unique(arr)) // ['1','2','3','a','b']
filter
let arr = [1,2,2,2,5,3,4,5,1] const unique = arr => { return arr.filter((ele,index, array) =>{ return index === array.indexOf(ele) }) } let v = unique(arr) console.log(v)
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']
reduce
let arr = ['1', '2', '3', '1', 'a', 'b', 'b'] const unique = arr.reduce((map, item) => { map[item] = 0 return map }, {}) console.log(Object.keys(unique)) // ['1','2','3','a','b']
3、翻转字符串
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], max = 0; arr.forEach(value => { if (value < min) min = value if (value > max) max = value }) return max - min ; } console.log(difference(arr)) // 74
冒泡