正则语法

  1. function _morenum(arr) {
  2. let a = [...new Set(arr)]
  3. let b = arr.join('')
  4. let c = []
  5. for (let i = 0; i < a.length; i++) {
  6. let d = a[i]
  7. let reg = `/${d}/g`
  8. // console.log(b.match(reg));
  9. c.push({ k: d, v: b.match(eval(reg)).length })
  10. }
  11. return c.sort((a, b) => b.v - a.v)[0].k
  12. }
  13. console.log(_morenum([1, 2, 1, 1, 1, 2, 2, 2, 2]));

使用Map方法

  1. function _morenum(arr) {
  2. let c = new Map()
  3. let res = 0;
  4. let key = null
  5. for (let i = 0; i < arr.length; i++) {
  6. if (!c.has(arr[i])) {
  7. c.set(arr[i], 1)
  8. } else {
  9. let a = c.get(arr[i])
  10. c.set(arr[i], ++a)
  11. }
  12. if (res < c.get(arr[i])) {
  13. res = c.get(arr[i])
  14. key = arr[i]
  15. }
  16. }
  17. return key
  18. // for (let i of c) {
  19. // if (i[1] == Math.max.apply(null, [...c.values()])) {
  20. // return i[0]
  21. // }
  22. // }
  23. }
  24. console.log(_morenum([1, 2, 1, 1, 1, 2, 2, 2, 2]));