2 回答
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>
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);
添加回答
举报