已解决-如何找到包含在单独数组中的两个值的百分比份额?

时间:2019-07-03 16:44:36

标签: javascript node.js

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

我有一个以下格式的对象:

{
   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%"}]
}

有人可以帮助我吗?我做不到。

2 个答案:

答案 0 :(得分:0)

我想到了这种愚蠢的技术,但是您可以尝试更多的方法。

我将所有数据分组为一个数组,但是将其objectKey(红色,绿色或其他任何颜色)和indexKey保留为Symbol(),因此不会有任何名称-干扰。

let data = {
    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%"}
    ]
}

let temp = [], objectKey = Symbol("object"), indexKey = Symbol("index")
for(let object in data) {
    temp = [ ...temp, ...data[object].map((x, index) => ({ ...x, [objectKey]: object, [indexKey]: index }))]
}

temp如下所示:

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

现在,我将按时间对所有数据进行分组:

let temp2 = temp.reduce((r, a) => (r[a.time] = r[a.time] || [], r[a.time].push(a), r), {});

所以我们得到temp2像这样:

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

现在我可以获取每个组的总和,获取所需的百分比并将其保存到正确的位置:

for(let time in temp2) {
    let sum = temp2[time].reduce((r, a) => (r + parseInt(a.value)), 0)
    temp2[time].forEach(e => (data[e[objectKey]][e[indexKey]].share = (e.value / sum * 100) + "%"))
}

答案 1 :(得分:0)

简短的解决方案:

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