2 回答

TA貢獻(xiàn)1824條經(jīng)驗(yàn) 獲得超6個(gè)贊
您可以使用_.countBy()
來獲取帶有計(jì)數(shù)的名稱對(duì)象,或者_.groupBy()
如果您想要帶有數(shù)組的名稱對(duì)象。
使用_.groupBy()
and的數(shù)組數(shù)組_.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>
和計(jì)數(shù)的對(duì)象_.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>
更新 - 要獲取組合鍵和值的字符串?dāng)?shù)組,您可以使用_.countBy(),然后使用_.map()它(lodash 也_.map()適用于對(duì)象)。
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貢獻(xiàn)2003條經(jīng)驗(yàn) 獲得超2個(gè)贊
1)_.countBy
生成對(duì)象的名稱,名稱/計(jì)數(shù)作為鍵/值。
2)_.entries
用于將對(duì)象轉(zhuǎn)換為一組嵌套條目數(shù)組。
3)_.map
在條目上產(chǎn)生所需的輸出。
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實(shí)現(xiàn)使用(幾乎)相同數(shù)量的代碼同樣的事情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);
添加回答
舉報(bào)