Javascript 使用百分比计算减少对象数组
我正在处理一系列对象,如:Javascript 使用百分比计算减少对象数组,javascript,arrays,Javascript,Arrays,我正在处理一系列对象,如: const data = [ {type: "Liberator", style: "Moderately Logical"}, {type: "Protector", style: "Somewhat Passionate"}, {type: "Energizer", style: "Balanced"}, {type: "Observer", style: "Balanced"}, {type: "Protector", style: "Bal
const data = [
{type: "Liberator", style: "Moderately Logical"},
{type: "Protector", style: "Somewhat Passionate"},
{type: "Energizer", style: "Balanced"},
{type: "Observer", style: "Balanced"},
{type: "Protector", style: "Balanced"},
{type: "Liberator", style: "Moderately Logical"},
];
我希望减少(我认为)数组中所有项目的汇总百分比细分
例如,最高级别的“保护器”=6分之2或33%。对于每个“保护者”,在2种风格中有1种是“有点激情的”,另一种是“平衡的”,占50%
预期结果:
const result = [
{
type: "Liberator",
percent: "33%",
[{
style: "Moderately Logical",
percent: "100%",
}],
},
{
type: "Protector",
percent: "33%",
[{
style: "Somewhat Passionate",
percent: "50%",
},{
style: "Balanced",
percent: "50%",
}],
},
{
type: "Observer",
percent: "17%",
[{
style: "Balanced",
percent: "100%",
}],
},
{
type: "Energizer",
percent: "17%",
[{
style: "Moderately Logical",
percent: "100%",
}],
},
];
我已成功地使用缩减后的原始数组,但现在不确定如何继续计算每个条目:
data.filter((d, index, self) =>
index === self.findIndex(t => (
t.type === d.type && t.style === d.style
)),
);
为此,可以先计算每种类型和样式的计数,然后计算它们的百分比:
const数据=[
{类型:“解放者”,样式:“适度逻辑”},
{类型:“保护者”,样式:“有点激情”},
{类型:“激发器”,样式:“平衡”},
{类型:“观察者”,样式:“平衡”},
{类型:“保护者”,样式:“平衡”},
{类型:“解放者”,样式:“适度逻辑”},
];
功能百分比(arr){
const total=arr.reduce((a,c)=>a+c.count,0);
返回arr.map(({count,…props})=>
({…道具,百分比:Math.round((count*100)/total)+'%');
}
常数计数=数据减少((a,c)=>{
a[c.type]=a[c.type]|{type:c.type,计数:0,样式:{};
a[c.type].count++;
a[c.type].styles[c.style]=a[c.type].styles[c.style]|{style:c.style,计数:0};
a[c.type].styles[c.style].count++;
返回a;
}, {});
const result=toPercent(对象值(计数))
.map(({styles,…props})=>({…props,styles:toPercent(Object.values(styles))});
控制台日志(结果)代码>您可以通过首先计算每种类型和样式的计数,然后计算它们的百分比来完成此操作:
const数据=[
{类型:“解放者”,样式:“适度逻辑”},
{类型:“保护者”,样式:“有点激情”},
{类型:“激发器”,样式:“平衡”},
{类型:“观察者”,样式:“平衡”},
{类型:“保护者”,样式:“平衡”},
{类型:“解放者”,样式:“适度逻辑”},
];
功能百分比(arr){
const total=arr.reduce((a,c)=>a+c.count,0);
返回arr.map(({count,…props})=>
({…道具,百分比:Math.round((count*100)/total)+'%');
}
常数计数=数据减少((a,c)=>{
a[c.type]=a[c.type]|{type:c.type,计数:0,样式:{};
a[c.type].count++;
a[c.type].styles[c.style]=a[c.type].styles[c.style]|{style:c.style,计数:0};
a[c.type].styles[c.style].count++;
返回a;
}, {});
const result=toPercent(对象值(计数))
.map(({styles,…props})=>({…props,styles:toPercent(Object.values(styles))});
控制台日志(结果)代码>