Open mbostock opened 7 years ago
I think it would be useful under the same name transpose, but with that name it absolutely must be involutive, ie transpose back [ {year: 2001, value: 1}, {year: 2002, value: 2}]
to {year: [2001, 2002], value: [1, 2]}
. Which makes auto-detection a bit harder (array of array, array of objects, object of arrays).
I've made a few tests here https://observablehq.com/d/e546523c2f1fbe2f
Perhaps it’s worth introducing two new methods: one for converting an array of objects to an object of arrays, and another for converting an object of arrays to an array of objects. Somewhat related, there’s also been a discussion on a pivot operation #142.
Since there does not seem to be a conflict of definitions, I prefer to use transpose for the four cases: arrays of arrays [[]], arrays of objects [{}], objects of arrays {[]} and objects of objects {{}}. https://github.com/d3/d3-array/pull/158
We have transpose(matrix) which transposes the rows and columns of a matrix (an array of arrays). But you might want similar functionality to transpose an object whose values are arrays into an array whose elements are objects.
Where:
Returns:
Should we try to overload d3.transpose to do both?
If so, how? The above implementation sort-of works for array-of-array input such as
transpose([[0, 1, 2], [3, 4, 5]])
, but returns an array of objects rather than an array of arrays. You could use Array.isArray to test whether the input is an Array and branch the behavior accordingly.If not, what name should this new method have? transposeObject?
Also, if transpose(object) given an object whose values are arrays returns an array of objects, then transpose(array) given an array whose elements are objects should return an object whose values are arrays.
Maybe this is too magical.