第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

如何使用 lodash 或 javascript 按數(shù)組分組

如何使用 lodash 或 javascript 按數(shù)組分組

qq_花開花謝_0 2022-01-07 13:20:15
一個(gè)數(shù)組如下:let names = [             'Aditya',             'Aditya',             'Aditya',             'Abhi',             'Abhi',             'goyal'            ]我想使用 lodash 函數(shù)并轉(zhuǎn)換將返回我的名稱數(shù)組[  Aditya(3),  Abhi(2),  goyal(1)]
查看完整描述

2 回答

?
慕妹3242003

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>


查看完整回答
反對(duì) 回復(fù) 2022-01-07
?
湖上湖

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);


查看完整回答
反對(duì) 回復(fù) 2022-01-07
  • 2 回答
  • 0 關(guān)注
  • 252 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)