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.
  • 8,016
  • 6
  • 40
  • 62
Sergei Basharov
  • 51,276
  • 73
  • 200
  • 335

2 Answers2

9

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.
  • 8,016
  • 6
  • 40
  • 62
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