Lodash typescript -将多个数组组合成一个数组,并对每个数组执行计算



我有一个Record<string,>并尝试对这些值进行计算。

输入示例:

const input1 = {
key1: [
[2002, 10],
[2003, 50],
],
};
const input2 = {
key1: [
[2002, 20],
[2003, 70],
],
};
const input3 = {
key1: [
[2002, 5],
[2003, 60],
],
};

对于每个键,对于特定年份,我想执行以下操作

year => input1 + input2 - input3
// output: 2002 => 25, 2003 => 60

我一直在使用lodash/fp。

map(a => a.map(nth(1)))(map('key1')([input1, input2]))
// [[10, 50], [20, 70], [5, 60]]

是否有某种方式传递输入并迭代它们,并以某种方式获得回调函数以获取执行计算的值。

我尝试了zip,zipWith,但没有取得任何进展。

在这种情况下我能做什么?

谢谢你的帮助。

您可以使用_.fromPairs方法获得对象,然后使用_.mergeWith进行加减。

const input1 = {
key1: [
[2002, 10],
[2003, 50],
],
};
const input2 = {
key1: [
[2002, 20],
[2003, 70],
],
};
const input3 = {
key1: [
[2002, 5],
[2003, 60],
],
};

const [one, two, three] = _.map([input1, input2, input3], ({key1 }) => _.fromPairs(key1))
const add = _.mergeWith(one, two, (a, b) => a + b)
const sub = _.mergeWith(add, three, (a, b) => a - b)
console.log(add)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>

最新更新