所以我有这样一个数组:
const colors = ['blue', 'blue', 'red', 'red', 'red', 'green', 'green', 'white']
我希望使用JavaScript输出相似项的百分比。
例如,蓝色和绿色应该各占总数组中8(100%)项的25%,红色占37.5%,而白色则占12.5%。
如何实现呢?
所以我有这样一个数组:
const colors = ['blue', 'blue', 'red', 'red', 'red', 'green', 'green', 'white']
我希望使用JavaScript输出相似项的百分比。
例如,蓝色和绿色应该各占总数组中8(100%)项的25%,红色占37.5%,而白色则占12.5%。
如何实现呢?
首先需要找到每个唯一的颜色,然后遍历它们以确定有多少个。一旦确定了数量,就可以通过 (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%
*/
Set
。只需使用一个对象 { blue: ..., red: ..., ... }
- undefined1 / 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))
这可以帮助:
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)
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; }