首页 > 解决方案 > 如何找到包含在不同数组中的两个值的百分比份额?

问题描述

我需要一点帮助来解决问题,我想看看是否有人可以帮助我:

我有以下格式的对象:

{
   red: [
      {time: "00:00:05", value: "7"},
      {time: "00:00:10", value: "3"}],
   green: [
     {time: "00:00:05", value: "3"},
      {time: "00:00:10", value: "27"}]
}

我需要做什么:

它的外观示例:

{
   red: [
      {time: "00:00:05", value: "7", share: "70%"},
      {time: "00:00:10", value: "3", share: "10%"}],
   green: [
     {time: "00:00:05", value: "3", share: "30%"},
      {time: "00:00:10", value: "27", share: "90%"}]
}

有人能帮我吗?我不能做到这一点。

标签: javascriptnode.js

解决方案


简短而简单的解决方案:

const o = {
  red: [
    {time: "00:00:05",value: "7"},
    {time: "00:00:10",value: "3"}
  ],
  green: [
    {time: "00:00:05",value: "3"},
    {time: "00:00:10",value: "27"}
  ]
};
const colors = Object.keys(o);

// saves the sum of all values, for each time
const total = o[colors[0]]
  .map(x => x.time)
  .map(time => colors
    .map(c => +o[c].find(x => x.time == time).value)
    .reduce((a, b) => a + b, 0)
  );
  
// adds the 'share' property
colors.forEach(c => o[c].forEach((x, i) => o[c][i].share = `${Math.floor(100*x.value/total[i])}%`))
console.log(o);


推荐阅读