【问题标题】:JS Find percentage of items in an arrayJS查找数组中项目的百分比
【发布时间】:2020-05-23 17:55:18
【问题描述】:

所以我有这个数组:

const colors = ['blue', 'blue', 'red', 'red', 'red', 'green', 'green', 'white']

我想使用 JavaScript 输出相似项目的百分比。

例如蓝色和绿色应各占 25%,红色占 37.5%,白色占 12.5%,共 8 (100%) 个数组。

我如何做到这一点?

【问题讨论】:

  • 到目前为止你有什么尝试?
  • 计算唯一值并将它们的数量除以数组的长度
  • 我不想用代码给出完整的答案,因为这听起来像是一个家庭作业问题。但我会给你步骤。 - 首先,您需要将数组的长度分配给一个常数。然后,对于每种独特的颜色,您需要计算该颜色在数组中出现的次数。您可以为此使用 array.filter。 - 最后,您需要将每种颜色的出现次数除以数组的长度,然后得出百分比。
  • 对不起,我的实际问题是我不知道如何从数组中获取唯一值。那应该是我的问题。罗布谢天谢地回答了

标签: javascript arrays percentage


【解决方案1】:

您首先需要找到每种独特的颜色,然后遍历它们以找出有多少种颜色。一旦你有了这个,你可以将百分比计算为(num * 100 / total)。

看看这个:

const colors = ['blue', 'blue', 'red', 'red', 'red', 'green', 'green', 'white']

const totalItems = colors.length
const uniqueItems = [...new Set(colors)]
uniqueItems.forEach(currColor => {
  const numItems = colors.filter(color => color === currColor) 
  console.log(`color ${currColor} represents ${numItems.length * 100 / totalItems}%`)
})
/*
color blue represents 25%
color red represents 37.5%
color green represents 25%
color white represents 12.5%
*/

【讨论】:

  • 谢谢 Rob,所以我的实际问题应该是如何从数组中找到唯一值。由于我不知道 Set() 我无法处理百分比,但是一旦我有了唯一值以及数组长度,剩下的就很简单了。
  • @Parsa 你不需要Set。只需取一个对象{ blue: ..., red: ..., ... }
  • 仅供参考:如果您担心性能,这个答案并不好,因为每种颜色都有一个过滤器。
【解决方案2】:

这会有所帮助:

const colors = ['blue', 'blue', 'red', 'red', 'red', 'green', 'green', 'white']

var data ={}

colors.map(el=>{
  if(!data[el]){
    return data[el]=colors.filter(ob=>ob===el).length*100/colors.length
     }
  })
console.log(data)

【讨论】:

  • 为什么要使用 .map()?为什么不使用 .forEach()?
  • 好的,.map() 是我的第一个想法,但我可以尝试 .forEach()
  • 谢谢,是的,这也可以,使用 map 我得到一个返回的数组,我可以循环显示百分比
【解决方案3】:

到目前为止,其他答案分多个步骤进行。但是使用reduce 对数据进行单次传递是相当简单的,注意每个实例添加1 / array.length 的一部分,因此添加100 / array.length 的百分比。这是一种技术:

const percentages = (xs) =>
  xs .reduce ((pcts, x) => ({...pcts, [x]: (pcts [x] || 0) + 100 / (xs .length)}), {})

const colors = ['blue', 'blue', 'red', 'red', 'red', 'green', 'green', 'white']

console .log (percentages (colors))

【讨论】:

  • 谢谢斯科特!我总是很高兴看到解决问题的不同方法。
【解决方案4】:

您可以将对象作为哈希映射并计算出现次数。然后获取哈希图的条目,并返回一个颜色数组和百分比值。

const
    colors = ['blue', 'blue', 'red', 'red', 'red', 'green', 'green', 'white'],
    percents = Object
        .entries(colors.reduce((map, color) => (map[color] = (map[color] || 0) + 1, map), {}))
        .map(([color, count]) => [color, count * 100 / colors.length]);

console.log(percents);
.as-console-wrapper { max-height: 100% !important; top: 0; }

【讨论】:

  • 谢谢尼娜!也很高兴看到你的方法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-16
  • 2020-11-22
  • 2018-09-09
  • 1970-01-01
  • 2013-03-07
  • 1970-01-01
相关资源
最近更新 更多