Nasir Ahmed
Nasir Ahmed

Reputation: 521

Want to merge arrays in columnwise to another array

Javascript newbie here. I have three arrays:

var code = [123, 456, 789];
var year = [2013, 2014, 2015];
var period = [3, 4, 5];

And I want to merge them like

var all = [
  {"code": 123, "year": 2013, "period": 3},
  {"code": 456, "year": 2014, "period": 4},
  {"code": 789, "year": 2015, "period": 5}
];

How can I easily do this in plain Javascript?

Upvotes: 0

Views: 154

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386520

You could use a dynamic approach with given keys in an array and an array for iterating with the data.

var code = [123, 456, 789],
    year = [2013, 2014, 2015],
    period = [3, 4, 5],
    keys = ['code', 'year', 'period'],
    result = [code, year, period].reduce(function (r, a, i) {
        a.forEach(function (v, j) {
            (r[j] = r[j] || {})[keys[i]] = v;
        });
        return r;
    }, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 0

Werner
Werner

Reputation: 2154

I'd prefer Alexandru-Ionut Mihai's solution but you may wan't it a bit more robust:

const len = Math.min(code.length, year.length, period.length);
let results = [];
for(let i = 0; i < len; i++) {
    results.push({
        code: code[i],
        year: year[i],
        period: period[i]
    });
}

Upvotes: 3

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48327

You should use map method, which has a callback function. map method creates new array by applying the provided function for every item.

var code = [123, 456, 789];
var year = [2013, 2014, 2015];
var period = [3, 4, 5];

console.log(code.map(function(item,i){
    return {"code":item,"year":year[i],"period":period[i]};
}))

Upvotes: 3

Related Questions