我需要一个函数,该函数采用对象数组input
,并创建其可以具有的所有不同组合,其值的总和为100,这在预期的output
中得到了部分证明。请注意,根据输出,也需要考虑secondaryType
。
我一直在想如何做到这一点,但自己却找不到答案。非常感谢您的帮助。
const input = [
{
type: 'A',
value: 10,
secondaryType: 'X'
},
{
type: 'B',
value: 20,
secondaryType: 'Y'
},
{
type: 'C',
value: 20,
secondaryType: 'Z'
},
{
type: 'D',
value: 20
},
{
type: 'E',
value: 30
}
]
输出:
[
{A: 10, B: 20, C: 20, D: 20, E: 30},
{X: 10, B: 20, C: 20, D: 20, E: 30},
{X: 10, Y: 20, C: 20, D: 20, E: 30},
etc...
];
答案 0 :(得分:1)
您需要获取类型,构建笛卡尔乘积并使用input
中的值映射对象。
const
input = [{ type: 'A', value: 10, secondaryType: 'X' }, { type: 'B', value: 20, secondaryType: 'Y' }, { type: 'C', value: 20, secondaryType: 'Z' }, { type: 'D', value: 20 }, { type: 'E', value: 30 }],
result = input
.map(({ type, secondaryType }) => secondaryType === undefined ? [type] : [type, secondaryType] )
.reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []))
.map(a => Object.fromEntries(a.map((k, i) => [k, input[i].value])));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }