Data manipulation with JavaScript


Suppose we have two arrays describing some cashflow like these −

const months = ["jan", "feb", "mar", "apr"];
const cashflows = [
   {'month':'jan', 'value':10},
   {'month':'mar', 'value':20}
];

We are required to write a JavaScript function that takes in two such arrays. Our function should then construct a combined array of objects that contains an object for each month and the value of cash flow for that month.

Therefore, for the above array, the output should look like −

const output = [
   {'month':'jan', 'value':10},
   {'month':'feb', 'value':''},
   {'month':'mar', 'value':20},
   {'month':'apr', 'value':''}
];

Example

The code for this will be −

const months = ["jan", "feb", "mar", "apr"];
const cashflows = [
   {'month':'jan', 'value':10},
   {'month':'mar', 'value':20}
];
const combineArrays = (months = [], cashflows = []) => {
   let res = [];
   res = months.map(function(month) {
      return this[month] || { month: month, value: '' };
   }, cashflows.reduce((acc, val) => {
      acc[val.month] = val;
      return acc;
   }, Object.create(null)));
   return res;
};
console.log(combineArrays(months, cashflows));

Output

And the output in the console will be −

[
   { month: 'jan', value: 10 },
   { month: 'feb', value: '' },
   { month: 'mar', value: 20 },
   { month: 'apr', value: '' }
]

Updated on: 24-Nov-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements