

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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: '' } ]
- Related Questions & Answers
- Data Manipulation Commands in DBMS
- File system manipulation
- What are the types of Data Manipulation Instructions in Computer Architecture?
- Matrix manipulation in Python
- C++ Floating Point Manipulation
- Bit manipulation program in 8051
- Array Type Manipulation in C++
- String manipulation instructions in 8086 microprocessor
- Bits manipulation (Important tactics) in C++
- Convert Image to Data URI with JavaScript
- What is Python module for date manipulation?
- What are Python modules for date manipulation?
- ipaddress - IPv4/IPv6 manipulation library in Python
- Array Manipulation and Sum using C/C++
- Reserve memory in Arduino for string manipulation
Advertisements