-1

What would be the best way to combine the two arrays below to get the desired result. I would want them to be combined by index.

Input is:

var array1 = [[1,2,3,4],[4,5,6,7]]
var array2 = [[a,b,c,d],[e,f,g,h]]

Desired output would be:

var array3 =[{
              array1:[1,2,3,4],
              array2:[a,b,c,d]
             },
             {
              array1:[4,5,6,7],
              array2:[a,b,c,d]
             }]

Any variation of the output would work as long as they are grouped by indexes. Thanks in advance.

EDIT: not a duplicate of what was suggestion. Suggestion out [a,1,b,2] and does not group the way the desired output shows.

Jarad Kears
  • 114
  • 2
  • 11

3 Answers3

2

I think you are looking for matrix transposition, where the 2d array passed is [array1, array2].

Edit: It looks like this operation can also be called "zipping" when only two arrays are used. Matrix transposition can support any number of rows, not just two.

var array1 = [
  [1, 2, 3, 4],
  [4, 5, 6, 7]
]
var array2 = [
  ['a', 'b', 'c', 'd'],
  ['e', 'f', 'g', 'h']
]

function transpose(matrix) {
  return matrix.map(function(_, i) {
    return matrix.map(function(e) {
      return e[i]
    })
  })
}

var result = transpose([array1, array2])

console.log(result)
.as-console-wrapper { min-height: 100%; }

If you really want to have nested objects with properties array1 and array2 instead of arrays, the following solution should also work (a variation of this answer):

var array1 = [
  [1, 2, 3, 4],
  [4, 5, 6, 7]
]
var array2 = [
  ['a', 'b', 'c', 'd'],
  ['e', 'f', 'g', 'h']
]


var result = array1.map(function (e1, i) {
  return { array1: e1, array2: array2[i] }
})

console.log(result)
.as-console-wrapper { min-height: 100%; }
Community
  • 1
  • 1
gyre
  • 16,369
  • 3
  • 37
  • 47
2

This is very similar to How do I zip two arrays in JavaScript?, except you just change the output format from an array to an object:

var array1 = [[1,2,3,4],[4,5,6,7]];
var array2 = [['a','b','c','d'],['e','f','g','h']];

var array3 = array1.map(function(_, i) {
  return {
    array1: array1[i],
    array2: array2[i]
  };
});

console.log(array3);
Community
  • 1
  • 1
4castle
  • 32,613
  • 11
  • 69
  • 106
  • Oh that is actually the same, for some reason when I clicked on the jsfiddle demo for the answer of that question. And modified the inputs and outputs it didn't come out properly. – Jarad Kears Mar 30 '17 at 18:59
0

You can use the array map function:

var array1 = [[1,2,3,4],[4,5,6,7]];
var array2 = [['a','b','c','d'],['e','f','g','h']];

var array3 = array1.map(function (e, i) {
    return [e, array2[i]];
});

console.log(array3);
snanda
  • 272
  • 4
  • 15