我可以得到我的价值观,谢谢。
答案 0 :(得分:0)
假设标签最终为["Pitcher","Pitcher","Catcher","Batter"];
const tags = ["Pitcher","Pitcher","Catcher","Batter"];
const result = Object.entries(tags.reduce((r,t)=>(r[t]=(r[t]||0)+1,r),{})).map(([k,v])=>`<li key="${k}">${k} - ${v}</li>`).join('\n');
console.log(result);
当然,由于您看不到标签的确切使用方式,因此很有可能标签更像
const tags = ["","Pitcher","","Pitcher","","Catcher","","Batter"];
const result = Object.entries(tags.reduce((r,t)=>(r[t]=(r[t]||0)+1,r),{})).map(([k,v])=>`<li key="${k}">${k} - ${v}</li>`).join('\n');
console.log(tags.join('')); // you can't see the empty tags here
console.log(result); // but this is the result
这就是为什么我要求您发布attendance
是什么,以查看数据发生了什么情况
但是,按照我的建议使用过滤器...
const tags = ["","Pitcher","","Pitcher","","Catcher","","Batter"];
const result = Object.entries(tags.filter(t=>t).reduce((r,t)=>(r[t]=(r[t]||0)+1,r),{})).map(([k,v])=>`<li key="${k}">${k} - ${v}</li>`).join('\n');
console.log(tags.join('')); // you can't see the empty tags here
console.log(result); // with filter, everything is good again
答案 1 :(得分:-1)
如果tags
是一个字符串数组(标签名称),则可以使用reduce
来获得所需的输出。
示例
var tags = ['Pitcher', 'Pitcher', 'Catcher', 'Batter', 'Batter'];
var result = tags.reduce((acc, val) => {
acc[val] = acc[val] || 0;
acc[val] = acc[val] + 1;
return acc;
}, {});
console.log(result);
希望这会有所帮助!
修改
要将最终对象转换为字符串数组,可以使用.map
Object.entries(result).map(([k, v]) => `${k}-${v}`);
感谢Jaromanda X