Search code examples
javascriptlodash

concat multiple 2 dimensional arrays with lodash


I have multiple 2 dimensional arrays that I would like to concat into a single 2 dimensional array:

var data = [
  [["x"], ["value1"], ["value2"], ["valu3"]],
  [["data1"], [0], [1], [2]],
  [["data2"], [2], [1], [0]]
];

wanted result:

var result = [
  ["x", "data1", "data2"],
  ["value1", 0, 2],
  ["value2", 1, 1],
  ["value3", 2, 0]
];

So far I am try to zip and concat using apply but I can't have the result I want:

var data = [
  [["x"], ["value1"], ["value2"], ["valu3"]],
  [["data1"], [0], [1], [2]],
  [["data2"], [2], [1], [0]]
];

var result = _.zipWith.apply(_, _.concat(data))

console.log(result)
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>


Solution

  • Using lodash transposing the matrix is as simple as this:

    _.zipWith(...data, _.concat)

    var data = [
      [["x"], ["value1"], ["value2"], ["valu3"]],
      [["data1"], [0], [1], [2]],
      [["data2"], [2], [1], [0]]
    ]
    var res = _.zipWith(...data, _.concat);
    
    console.log(res);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

    And also in Vanilla JS this is as simple as this

    data[0].map((_,i)=>data.map(r=>r[i][0]))

    var data = [
      [["x"], ["value1"], ["value2"], ["valu3"]],
      [["data1"], [0], [1], [2]],
      [["data2"], [2], [1], [0]]
    ];
    
    var res = data[0].map((_,i)=>data.map(r=>r[i][0]));
    
    console.log(res);

    Note: You don't even need the _.concat and only _.zip would work (without 2nd argument) if your each rows were not nested, in your data rows are not [A, B, C, ...]. your rows are [[A], [B], [C], ...] but in output you need simple array for rows, so the _concat is used to make them simple array for each resultant row. Similarly in plain JS version the [0] in r[i][0] is needed because we have a nested level data in each row, otherwise (for simple row as input) it could have been r[i]