d3 / d3-array

Array manipulation, ordering, searching, summarizing, etc.
https://d3js.org/d3-array
ISC License
454 stars 187 forks source link

transpose(object)? #48

Open mbostock opened 7 years ago

mbostock commented 7 years ago

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.

function transpose(object) {
  var m = 0;
  for (var k in object) m = Math.max(m, object[k].length);
  for (var i = -1, transpose = new Array(m); ++i < m;) {
    var o = transpose[i] = {};
    for (var k in object) {
      o[k] = object[k][i];
    }
  }
  return transpose;  
}

Where:

transpose({
  year: [2001, 2002],
  value: [1, 2]
})

Returns:

[
  {year: 2001, value: 1},
  {year: 2002, value: 2},
]

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.

Fil commented 4 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

mbostock commented 4 years ago

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.

Fil commented 4 years ago

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