js数组排序问题

实现对数据排序并按出现次数进行排序(用面向对象方式实现,用for循环的方式排序
[1,4,2,1,3,2,1,4]传入方法中,应该输出如下结果:
1出现了3次
2出现了2次
4出现了2次
3出现了1次

这个问题怎么写,求解,想了半天没想到好的写法

阅读 1.7k
2 个回答
var numCount = [1,4,2,1,3,2,1,4].reduce((numCount, num) => {
  if(numCount[num] == null) {
    numCount[num] = 0;
  }
  numCount[num]++;
  return numCount;
}, {})

Object.keys(numCount)
.map(key => ({num: +key, count: numCount[key]}))
.sort((a, b) => b.count - a.count)
.forEach(({num, count}) => {
  console.log(`${num}出现了${count}次`)
})
[1,4,2,1,3,2,1,4].reduce((rst, n) => {
    let obj = rst.find(({ name }) => n === name)
    if (!obj) {
      obj = { name: n, times: 1 }
      rst.push(obj)
    } else {
      obj.times += 1
    }
    return rst
  }, [])
  .sort(({ times: a, name: c }, { times: b, name: d }) => {
    if (b === a) return c - d
    return b - a
  })
  .forEach(({ name, times }) => {
    console.log(`${name}出现${times}次`)
  })
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题