Creates an array of elements, ungrouping the elements in an array produced by zip and applying the provided function.
Math.max()
and the spread operator (...
) to get the longest subarray in the array, Array.prototype.map()
to make each element an array.Array.prototype.reduce()
and Array.prototype.forEach()
to map grouped values to individual arrays.Array.prototype.map()
and the spread operator (...
) to apply fn
to each individual group of elements.const unzipWith = (arr, fn) =>
arr
.reduce(
(acc, val) => (val.forEach((v, i) => acc[i].push(v)), acc),
Array.from({
length: Math.max(...arr.map(x => x.length))
}).map(x => [])
)
.map(val => fn(...val));
unzipWith(
[
[1, 10, 100],
[2, 20, 200],
],
(...args) => args.reduce((acc, v) => acc + v, 0)
);
// [3, 30, 300]
JavaScript, Array
Creates an array of arrays, ungrouping the elements in an array produced by zip.
JavaScript, Array
Returns the elements that exist in both arrays, after applying the provided function to each array element of both.
JavaScript, Array
Creates an array of elements, grouped based on the position in the original arrays and using a function to specify how grouped values should be combined.