在JavaScript中如何找到数组中项目的百分比

3

所以我有这样一个数组:

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

我希望使用JavaScript输出相似项的百分比。

例如,蓝色和绿色应该各占总数组中8(100%)项的25%,红色占37.5%,而白色则占12.5%。

如何实现呢?


1
你到目前为止尝试了什么? - undefined
1
计算唯一值的数量,并将其数量除以数组的长度。 - undefined
我宁愿不用代码给出完整答案,因为这听起来像是一个作业问题。但是我可以给你一些步骤。首先,你需要将数组的长度赋值给一个常量。然后,对于每个唯一的颜色,你需要计算该颜色在数组中出现的次数。你可以使用数组过滤器来实现这一点。最后,你需要将每种颜色的出现次数除以数组的长度,这样就可以得到百分比了。 - undefined
抱歉,伙计们,我的实际问题是我不知道如何从数组中获取唯一的值。这本应该是我的问题。幸运的是,Rob回答了它。 - undefined
4个回答

3

首先需要找到每个唯一的颜色,然后遍历它们以确定有多少个。一旦确定了数量,就可以通过 (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%
*/

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

2
到目前为止,其他的回答都需要多个步骤才能完成。但是,使用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))


1
谢谢你,Scott!我总是很欣赏看到对问题有不同的解决方法。 - undefined

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()? - undefined
好的,.map() 是我的第一个想法,但我可以尝试一下 .forEach()。 - undefined
谢谢,是的,这也可以工作,使用map函数我可以得到一个返回的数组,我可以循环显示百分比。 - undefined

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

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


谢谢妮娜!很高兴看到你的方法。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接