javascript - 如何计算数组中的值并将它们设置在新数组中的对象中?(Javascript)
问题描述
所以基本上我有一个包含大量单词的数组。我想实现一个新数组,它将单词和单词的数量作为对象的属性。像这样:
const arrayWithWords = [`word1`, `word2`, `word5`, `word1`, `word3`, `word6`, `word2`, `word3`, `word1`, `word5`]
// and I want to achieve the array below
const newArray = [ {name: `word1`, amount: 3} {name: `word2`, amount: 2} {name: `word3`, amount: 2} {name: `word4`, amount: 0} {name: `word5`, amount: 2} {name: `word6`, amount:1}]
我试过使用 for 循环,但我总是卡住。对此有什么可能的解决方案?
解决方案
您可以通过计算频率轻松解决它。
const arrayWithWords = [
`word1`,
`word2`,
`word5`,
`word1`,
`word3`,
`word6`,
`word2`,
`word3`,
`word1`,
`word5`,
];
let ret = arrayWithWords.reduce((p, c) => {
if (!p[c]) p[c] = 1;
else p[c] += 1;
return p;
}, {});
ret = Object.entries(ret).map((x) => ({ name: x[0], amount: x[1] }));
console.log(ret);
推荐阅读
- python - cifar10 数据的 gabor 过滤器实现
- linux - 在添加到 PATH 时动态声明一个环境变量
- azure - Azure CDN - 从 *.azurewebsites.net 重定向到 cdn 生成 ERR_TOO_MANY_REDIRECTS 错误
- php - 合并远程存储的 PDF Laravel
- laravel - 如何在刀片 laravel 8 中获取选择输入的旧值?
- javascript - 使用 i18n 从 svelte store 中导出一个简单的数据对象
- reactjs - 如何改进过滤器 ReactJS
- python - 在 python 中,将函数用作类的属性的正确语法是什么?
- amazon-web-services - 具有动态环境变量的 Elastic Beanstalk app.config option_settings 不起作用
- python - 从 pandas Dataframe 列创建列表的高效/Pythonic 方式