I have data that I need to gather in a very specific way. Right now, the data comes in the form of N arrays (of arrays) all of M length. M will be the same for all arrays for a given invocation.
So the following example has N=2 and M=3. The length of the final nested arrays is variable and can be 0 or more (but it will be an empty array of length zero)
[
[
['a', 'b'], ['c'], ['d']
],
[
['e'], ['f', 'g'], ['h']
]
]
What I need is
[['a', 'b', 'e'], ['c', 'f', 'g'], ['d', 'h']]
I can get a working answer but it’s gross, and I was hoping someone had a more elegant approach.
Here’s the (sort of) working solution:
const gatheredData = [[]];
const final = _.forEach(startData, (array, arrayIndex) => {
// This is intended to handle the basecase creation of empty arrays
if (_.size(gatheredData) < arrayIndex) {
gatheredData.concat([]);
}
gatheredData[arrayIndex].concat(array);
});
That also seems to error out in edge cases I haven’t quite drilled down into yet.
5
Answers
You can use
mergeWith
One option without lodash would be to first map the nested array within your array, where for each inner (leaf) array (eg:
['a', 'b']
), you concatenate with an array containing all inner elements at the same index (that you can obtain with mapping all other arrays), eg:This seems to do the trick:
You can use
map
andflatMap
like this:with lodash you can use
_.unzipWith()
, and pass_.concat()
as the iteratee: