1

I have an array:

[ [1,2,3], [4,5,6] ]

How can I turn it into

[ [1,4], [2,5], [3,6] ]

I am sure it's something I can do easily with lodash but I have not found it in the docs.

Jose Ricardo Bustos M.
  • 7,881
  • 6
  • 39
  • 58
Sergei Basharov
  • 47,526
  • 63
  • 186
  • 320

2 Answers2

8

a solution using lodash

m = [ [1,2,3], [4,5,6] ];
t = _.zip.apply(_, m);
// result t = [ [1,4], [2,5], [3,6] ]
m = [ [1,1,1,1], [2,2,2,2], [3,3,3,3] ]
t = _.zip.apply(_, m);
// result t = [ [1,2,3], [1,2,3], [1,2,3], [1,2,3] ]

explanation:

apply: Make the call to a function with a given value for this and arguments passed as an array ..... is same that _.zip(arg0, arg1, arg2) similar _.zip.apply(null, m) where m = [arg0, arg1, arg2]

Jose Ricardo Bustos M.
  • 7,881
  • 6
  • 39
  • 58
0

_.zip(['fred', 'barney'], [30, 40], [true, false]); // → [['fred', 30, true], ['barney', 40, false]] // Official documentation

Official documentation. https://lodash.com/docs#zip

baquiax
  • 148
  • 13