Skip to content


Subversion checkout URL

You can clone with
Download ZIP


Iterative version of _.unzip #1049

wants to merge 1 commit into from

2 participants


As requested in #1047.

This is another option for the implementation of _.unzip. It's a lot faster and not much larger, not as pretty though :)


It now has the sparse issue (may return sparse arrays), again :3


It shouldn't do. The outer array is built up using push method calls and the inner arrays are created using the Array constructor with the complete length specified. Have I missed something?


Have I missed something?

Yap. Try 1 in _.unzip([[1], [2], [3, 'x']])[1]; // false, should be true
It's also ~29 bytes bigger than the old way that used _.each.


Ah, again a lack of understanding on my part. I thought Array(x) would produce a non-sparse array but I now see that to make an array non-sparse you need to assign to each element of it.


Well, as soon as I try and fix that problem it becomes a lot slower:

At this point the current version (unzipNoSparse in the jsperf, the one from pr #1047) isn't much slower. So this is making me think we should stick with that version, what do you think @michaelficarra?


@almost you might check out my implementation here.

@jashkenas jashkenas closed this in df2e9e4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Apr 4, 2013
  1. @almost
This page is out of date. Refresh to see the latest.
Showing with 10 additions and 2 deletions.
  1. +10 −2 underscore.js
12 underscore.js
@@ -506,8 +506,16 @@
// `[['a',1],['b',2],['c',3]]` returns the array
// [['a','b','c'],[1,2,3]].
_.unzip = function(tuples) {
- var maxLen = _.max(_.pluck(tuples, "length"))
- return _.times(maxLen, _.partial(_.pluck, tuples));
+ var result = [];
+ for(var i = 0; i < tuples.length; i++) {
+ for(var j = 0; j < tuples[i].length; j++) {
+ if (result.length === j) {
+ result.push(Array(tuples.length));
+ }
+ result[j][i] = tuples[i][j];
+ }
+ }
+ return result;
// Converts lists into objects. Pass either a single array of `[key, value]`
Something went wrong with that request. Please try again.