js实现字符串数组 按数组元素出现频率(次数)由大到小进行排序

出自面试官给我的一道题:

已知数组[‘a’,‘ab’,‘abc’,‘ab’,…],把数组按照字符串出现次数由大到小进行排序,建议通过编码实现

我写了两种输出结果:

由大到小排序,且去重

const arr = ['a', 'ab', 'abc', 'ab', 'a', 'abc', 'bc', 'ab']
const mapArr = new Map()  //创建一个Map结构数据
arr.map(item => {  //遍历数组
  if (mapArr.has(item)) {  //如果Map数据中存在当前项,给当前项值(即个数)+1
    let current = mapArr.get(item)
    mapArr.set(item, current += 1)
  } else {  //如果不存在,则添加该项并将它的个数设置为1
    mapArr.set(item, 1)
  }
})
//将map结构数据转换成数组对象,每一项也是数组的形式包裹的key和value 
const mapEntries = [...mapArr.entries()] 
// mapEntries  [ [ 'a', 2 ], [ 'ab', 3 ], [ 'abc', 2 ], [ 'bc', 1 ] ]
mapEntries.sort((pre, nxt) => {
  return pre[1] < nxt[1] ? 1 : -1
}) //给mapEntries 排序
const target = mapEntries.map(item => item[0])
console.log('target', target) //target [ 'ab', 'abc', 'a', 'bc' ]

由大到小排序,不去重

const arr = ['a', 'ab', 'abc', 'ab', 'a', 'abc', 'bc', 'ab']
const mapArr = new Map()
arr.map(item => {
  if (mapArr.has(item)) { //和上面的区别是,将Map结构的数据它的value值直接设置为遍历的每一项
    let current = mapArr.get(item).concat([item])
    mapArr.set(item, current)
  } else {
    mapArr.set(item, [item])
  }
})
//mapArr是这样的数据:Map(4) {
//  'a' => [ 'a', 'a' ],
//  'ab' => [ 'ab', 'ab', 'ab' ],
//  'abc' => [ 'abc', 'abc' ],
//  'bc' => [ 'bc' ]
//}
//然后再转成二维数组排序,再遍历降维
const mapEntries = [...mapArr.entries()]
mapEntries.sort((pre, nxt) => {
  return pre[1].length < nxt[1].length ? 1 : -1
})
const target = mapEntries.map(item => item[1]).flat()
console.log('target', target)
// target ['ab','ab','ab','abc','abc','a','a','bc']

遍历数组每项,计算相同项的个数

const arr = ['a', 'ab', 'abc', 'ab', 'a', 'abc', 'bc', 'ab']
const temp = arr.reduce((pre, nxt) => {
  if (nxt in pre) {
    pre[nxt]++
  } else {
    pre[nxt] = 1
  }
  return pre
}, {})
console.log(temp) //{ a: 2, ab: 3, abc: 2, bc: 1 }
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值