I have two arrays, each containing a years object with year key-value pairs and a value. I want to create an updated version of array1 with the values for the years in each row reduced by the values of the corresponding values in array2
i.e. A/Fred/2013 should be reduced from 16 times 3 to 13 and so on.
So far I have done it, but I can't update the array correctly.
array1.forEach(r1 => {
// Get the corresponding row from array2
let array2Record = array2.find(r2 => r2.key1 === r1.key1 && r2.key2 === r1.key2);
// Go through each of the years for this row in array1
Object.entries(r1.years).forEach(keyValuePair => {
// And reduce it by the value in array2
keyValuePair.value = keyValuePair.value - array2Record.years[keyValuePair.key].value;
})
})
This is the simplified version of the data.
let array1 = [
{
"key1": "A",
"key2": "Fred",
"years": {
"2013": 16,
"2014": 11,
"2015": 17
}
},
{
"key1": "A",
"key2": "Jim",
"years": {
"2013": 1,
"2014": 4,
"2015": 3
}
},
{
"key1": "B",
"key2": "Mary",
"years": {
"2013": 1,
"2014": 4,
"2015": 3
}
}
]
let array2 = [
{
"key1": "A",
"key2": "Fred",
"years": {
"2013": 3,
"2014": 2,
"2015": 7
}
},
{
"key1": "A",
"key2": "Jim",
"years": {
"2013": 9,
"2014": 3,
"2015": 1
}
},
{
"key1": "B",
"key2": "Mary",
"years": {
"2013": 8,
"2014": 3,
"2015": 6
}
}
]