Data manipulation with JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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: '' }
]
raja
Updated on 24-Nov-2020 10:36:38

Advertisements