问题描述
const sources = [
{ id : 0,type : "Project" },{ id : 1,type : "Board" },{ id : 2,type : "Fan" },{ id : 3,{ id : 4,{ id : 5,type : "Fan" }
]
是否有一个数组函数可以用来将计数映射到以下内容(无需通过 for 循环)
{
"Project": 3,"Board": 1,"Fan": 2
}
解决方法
Array reduce 可以为所欲为:
const sources = [
{ id : 0,type : "Project" },{ id : 1,type : "Board" },{ id : 2,type : "Fan" },{ id : 3,{ id : 4,{ id : 5,type : "Fan" }
]
// solution
const answer=sources.reduce((r,{type})=>(r[type]=(r[type]||0)+1,r),{});
console.log(answer);