- 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
Merge arrays in column wise to another array in JavaScript
Suppose, we have three arrays of numbers like these −
const code = [123, 456, 789]; const year = [2013, 2014, 2015]; const period = [3, 4, 5];
We are required to write a JavaScript function that takes in three such arrays. The function should then construct an array of objects based on these three arrays like this −
const output = [ {"code": 123, "year": 2013, "period": 3}, {"code": 456, "year": 2014, "period": 4}, {"code": 789, "year": 2015, "period": 5} ];
Example
The code for this will be −
const code = [123, 456, 789]; const year = [2013, 2014, 2015]; const period = [3, 4, 5]; const mergeColumnWise = (code = [], year = [], period = []) => { let results = []; for(let i = 0; i < code.length; i++) { results.push({ code: code[i], year: year[i], period: period[i] }); } return results; }; console.log(mergeColumnWise(code, year, period));
Output
And the output in the console will be −
[ { code: 123, year: 2013, period: 3 }, { code: 456, year: 2014, period: 4 }, { code: 789, year: 2015, period: 5 } ]
Advertisements