Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

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 }
]
Updated on: 2020-11-20T13:43:15+05:30

681 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements