javascript - 如何找到包含在不同数组中的两个值的百分比份额?
问题描述
我需要一点帮助来解决问题,我想看看是否有人可以帮助我:
我有以下格式的对象:
{
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%"}]
}
有人能帮我吗?我不能做到这一点。
解决方案
简短而简单的解决方案:
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);
推荐阅读
- c++ - QtCreator 中用于 C++ 类型的自动完成
- javascript - How to resume the submit request that was blocked by event.preventDefault(); when the function is executed
- python - Python Dash 嵌套 html ul 列表
- ios - 如何在 UISearchBar 中保存选定的范围按钮?
- java - Wildfly 10.1.0 IllegalStateException - UT000010 会话无效
- postgresql - 使用一些重叠的主键合并 2 个表 Postgres
- swift - Kotlin 是否有类似于 Swift Optional 的类型?
- ios - 滚动后的 Swift UICollectionView Cell 收藏按钮更改为不收藏
- cmake - 在 cmake 中使用 REQUIRED_FILES 进行单元测试
- python - Python AuthenticationError:gdax 无效的 API 密钥