首页 > 解决方案 > 如何计算数组中的值并将它们设置在新数组中的对象中?(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 循环,但我总是卡住。对此有什么可能的解决方案?

标签: javascriptarraysfor-loop

解决方案


您可以通过计算频率轻松解决它。

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


推荐阅读