- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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: '' } ]
Advertisements