Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
217 views
Welcome To Ask or Share your Answers For Others

1 Answer

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}次`)
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...