I have a Record<string, number[][]> and trying to perform calculation over these values.
An example input:
const input1 = { key1: [ [2002, 10], [2003, 50], ], }; const input2 = { key1: [ [2002, 20], [2003, 70], ], }; const input3 = { key1: [ [2002, 5], [2003, 60], ], };
For each key, and for the specific year I want to do the following
year => input1 + input2 - input3 // output: 2002 => 25, 2003 => 60
For this I have been playing around with lodash/fp.
map(a => a.map(nth(1)))(map('key1')([input1, input2])) // [[10, 50], [20, 70], [5, 60]]
is there a way to somehow pass the inputs and iterate over them, and somehow get a callback function to get the values to perform the calculation.
I tried zip
, zipWith
but didn’t get to anywhere with them.
Any clue what I can do in this instance?
Thank you for your help.
Advertisement
Answer
You could get an object with _.fromPairs
method and then use _.mergeWith
to add and subtract.
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>