I have two data sets from the same API call on two different dates and I want to calculate variance between values of those two arrays of objects received using javascript. The following are two data sets.
const arrayOne = [
{
id: 1,
values: {
sales: {
rawValue: 3,
value: '3.0',
},
},
},
{
id: 2,
values: {
sales: {
rawValue: 1,
value: '1.0',
},
},
},
];
const arrayTwo = [
{
id: 1,
values: {
sales: {
rawValue: 1.1,
value: '1.1',
},
},
},
{
id: 2,
values: {
sales: {
rawValue: 2,
value: '2.0',
},
},
},
];
I am trying to create a new array with the following objects with calculated variance init:
const newArray = [
{
id: 1,
values: {
salesVar: {
rawValue: calculatedVariance,
value: 'calculatedVariance',
},
},
},
{
id: 2,
values: {
salesVar: {
rawValue: calculatedVariance,
value: 'calculatedVariance',
},
},
},
];
Is there any possible solution for this using javascript?
2
Answers
Calculating variance is straightforward – the difficult part is navigating around the data structures.
Assuming the two arrays contain objects of the same shape and in the same order, then it is very simple to use Lodash’s
mergeWith
to combine the two. The function accepts a customiser argument which can do the calculation:In this case, the customiser only handles
rawValue
andvalue
properties. For everything else, the customiser just returnsundefined
which allows Lodash to handle the recursive merging by automatically.For the cases where the result is handled by the customiser,
calculateVariance()
handles the calculation, whilecalculateVarianceAsString()
formats the result usingIntl.NumberFormat#format()
to show a ".0" at the end of the number, even if it does not have fractional part. But Show as much of the fraction as possible otherwise.