通过百分比计算减少对象数组

时间:2018-12-18 20:45:28

标签: 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: "Balanced"},
  {type: "Liberator", style: "Moderately Logical"},
];

我希望将阵列减少(我认为)为阵列中所有项目的汇总百分比细分。

例如,最高级别的“保护器” = 6(即33%)中的2。对于每个“保护者”,在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
  )),
);

1 个答案:

答案 0 :(得分:2)

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

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