Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Merge arrays in column wise to another array in JavaScript
When working with multiple arrays, you often need to combine their elements column-wise to create structured data. This technique merges arrays by their corresponding indices to form an array of objects.
Problem Statement
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 need to merge these arrays column-wise to create an array of objects where each object contains the corresponding elements from all three arrays:
const output = [
{"code": 123, "year": 2013, "period": 3},
{"code": 456, "year": 2014, "period": 4},
{"code": 789, "year": 2015, "period": 5}
];
Using for Loop
The most straightforward approach uses a for loop to iterate through the arrays and construct objects:
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));
[
{ code: 123, year: 2013, period: 3 },
{ code: 456, year: 2014, period: 4 },
{ code: 789, year: 2015, period: 5 }
]
Using map() Method
A more functional approach uses the map() method for a cleaner solution:
const code = [123, 456, 789];
const year = [2013, 2014, 2015];
const period = [3, 4, 5];
const mergeWithMap = (code, year, period) => {
return code.map((codeVal, index) => ({
code: codeVal,
year: year[index],
period: period[index]
}));
};
console.log(mergeWithMap(code, year, period));
[
{ code: 123, year: 2013, period: 3 },
{ code: 456, year: 2014, period: 4 },
{ code: 789, year: 2015, period: 5 }
]
Generic Solution for Any Number of Arrays
For a more flexible approach that works with any number of arrays:
const mergeArraysGeneric = (keys, ...arrays) => {
const length = arrays[0].length;
return Array.from({ length }, (_, index) => {
const obj = {};
keys.forEach((key, keyIndex) => {
obj[key] = arrays[keyIndex][index];
});
return obj;
});
};
const keys = ['code', 'year', 'period'];
const code = [123, 456, 789];
const year = [2013, 2014, 2015];
const period = [3, 4, 5];
console.log(mergeArraysGeneric(keys, code, year, period));
[
{ code: 123, year: 2013, period: 3 },
{ code: 456, year: 2014, period: 4 },
{ code: 789, year: 2015, period: 5 }
]
Conclusion
Merging arrays column-wise is essential for transforming parallel data structures into objects. Use the for loop for simplicity or map() for a more functional approach.
