首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用百分比计算减少对象数组

用百分比计算减少对象数组
EN

Stack Overflow用户
提问于 2018-12-18 20:45:27
回答 1查看 529关注 0票数 0

我正在处理一组对象,如:

代码语言:javascript
复制
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或33%中的2。对于每一个“保护者”,有一个“有点激情”的2种风格,另一种是“平衡”50%。

预期结果:

代码语言:javascript
复制
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%",
    }],
  },
];

我已经成功地获得了简化的原始数组,但现在不确定如何对每个条目进行计算:

代码语言:javascript
复制
data.filter((d, index, self) =>
  index === self.findIndex(t => (
    t.type === d.type && t.style === d.style
  )),
);
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-12-18 21:17:39

您可以首先计算每种类型和样式的计数,然后计算它们的百分比:

代码语言:javascript
复制
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"},
];

function toPercent(arr) {
  const total = arr.reduce((a, c) => a + c.count, 0);
  return arr.map(({count, ...props}) => 
    ({ ...props, percent: Math.round((count * 100) / total) + '%'}));
}

const counts = data.reduce((a, c) => {
  a[c.type] = a[c.type] || {type: c.type, count: 0, styles: {}};
  a[c.type].count++;
  a[c.type].styles[c.style] = a[c.type].styles[c.style] || {style: c.style, count: 0};
  a[c.type].styles[c.style].count++;
  return a;
}, {});

const result = toPercent(Object.values(counts))
  .map(({styles, ...props}) => ({ ...props, styles: toPercent(Object.values(styles))}));
  
console.log(result);

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53840791

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档