为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用 lodash 或 javascript 按数组分组

如何使用 lodash 或 javascript 按数组分组

qq_花开花谢_0 2022-01-07 13:20:15
一个数组如下:let names = [             'Aditya',             'Aditya',             'Aditya',             'Abhi',             'Abhi',             'goyal'            ]我想使用 lodash 函数并转换将返回我的名称数组[  Aditya(3),  Abhi(2),  goyal(1)]
查看完整描述

2 回答

?
慕妹3242003

TA贡献1824条经验 获得超6个赞

您可以使用_.countBy()来获取带有计数的名称对象,或者_.groupBy()如果您想要带有数组的名称对象。

使用_.groupBy()and的数组数组_.values()

const names = ["Aditya","Aditya","Aditya","Abhi","Abhi","goyal"]


const result = _.values(_.groupBy(names))


console.log(result)

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

和计数的对象_.countBy

const names = ["Aditya","Aditya","Aditya","Abhi","Abhi","goyal"]


const result = _.countBy(names)


console.log(result)

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

更新 - 要获取组合键和值的字符串数组,您可以使用_.countBy(),然后使用_.map()它(lodash 也_.map()适用于对象)。


const names = ["Aditya","Aditya","Aditya","Abhi","Abhi","goyal"]


const result = _.map(_.countBy(names), (v, k) => `${k}(${v})`)


console.log(result)

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>


查看完整回答
反对 回复 2022-01-07
?
湖上湖

TA贡献2003条经验 获得超2个赞

1)_.countBy生成对象的名称,名称/计数作为键/值。

2)_.entries用于将对象转换为一组嵌套条目数组。

3)_.map在条目上产生所需的输出。

const names = ["Aditya","Aditya","Aditya","Abhi","Abhi","goyal"]


const toString = ([name, count]) => `${name}(${count})`;

const entries = _.entries(_.countBy(names));

const result = _.map(entries, toString);


console.log(result);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

另外,您可以用香草JS实现使用(几乎)相同数量的代码同样的事情reduce,Object.entries和map。


const names = ["Aditya","Aditya","Aditya","Abhi","Abhi","goyal"]


const counts = names.reduce((acc, c) => {

  return acc[c] = (acc[c] || 0) + 1, acc;

}, {});


const toString = ([name, count]) => `${name}(${count})`;

const entries = Object.entries(counts);

const result2 = entries.map(toString);


console.log(result2);


查看完整回答
反对 回复 2022-01-07
  • 2 回答
  • 0 关注
  • 195 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信