正则语法
function _morenum(arr) {
let a = [...new Set(arr)]
let b = arr.join('')
let c = []
for (let i = 0; i < a.length; i++) {
let d = a[i]
let reg = `/${d}/g`
// console.log(b.match(reg));
c.push({ k: d, v: b.match(eval(reg)).length })
}
return c.sort((a, b) => b.v - a.v)[0].k
}
console.log(_morenum([1, 2, 1, 1, 1, 2, 2, 2, 2]));
使用Map方法
function _morenum(arr) {
let c = new Map()
let res = 0;
let key = null
for (let i = 0; i < arr.length; i++) {
if (!c.has(arr[i])) {
c.set(arr[i], 1)
} else {
let a = c.get(arr[i])
c.set(arr[i], ++a)
}
if (res < c.get(arr[i])) {
res = c.get(arr[i])
key = arr[i]
}
}
return key
// for (let i of c) {
// if (i[1] == Math.max.apply(null, [...c.values()])) {
// return i[0]
// }
// }
}
console.log(_morenum([1, 2, 1, 1, 1, 2, 2, 2, 2]));