簡體   English   中英

如何返回列表中相同對象的計數?

[英]How to return count of this same object in the list?

我有一個這樣的日期列表:

[ "2020-08-20", "2020-08-20", "2020-08-21", "2020-08-24", "2020-08-25", "2020-08-25", "2020-08-25", ]

如何返回列表中相同項目的計數?

例如:

{date: "2020-08-20", count: 2},
{date: "2020-08-21", count: 1},
{date: "2020-08-24", count: 1},
{date: "2020-08-25", count: 3},

謝謝你的幫助

 const ary = [ "2020-08-20", "2020-08-20", "2020-08-21", "2020-08-24", "2020-08-25", "2020-08-25", "2020-08-25", ] const result = [] ary.forEach(d => { const index = result.findIndex(r => r.date === d) if (index === -1) { result.push({ date: d, count: 1 }) } else { result[index].count ++; } }) console.log(result)

您可以使用數組減少方法來計算它。 遍歷字符串數組並計算頻率。 最后使用Object.values方法打印結果。

 const data = [ '2020-08-20', '2020-08-20', '2020-08-21', '2020-08-24', '2020-08-25', '2020-08-25', '2020-08-25', ]; const ret = data.reduce((prev, c) => { const p = prev; if (!p[c]) p[c] = { date: c, count: 1 }; else p[c] = { date: c, count: p[c].count + 1 }; return p; }, {}); console.log(Object.values(ret));

我想你可以這樣:

 const yourArray = [ "2020-08-20", "2020-08-20", "2020-08-21", "2020-08-24", "2020-08-25", "2020-08-25", "2020-08-25", ] const result = yourArray .filter((item, pos) => yourArray.indexOf(item) == pos) .map(item => ({ date: item, count: yourArray.filter(current => current === item).length })) console.log(result)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM