unzipWith
arrays
This method is like unzip except that it accepts iteratee to specify how regrouped values should be combined.
Installation
Import
import { unzipWith } from '@tulx/utils';Source Code
Implementation
/**
* This method is like unzip except that it accepts iteratee to specify how regrouped values should be combined.
*
* @param array - The array of grouped elements to process.
* @param iteratee - The function to combine regrouped values.
* @returns The new array of regrouped elements.
*
* @example
* ```ts
* const zipped = zip([1, 2], [10, 20], [100, 200]);
* unzipWith(zipped, (...args) => args.reduce((a, b) => a + b, 0));
* // [111, 222]
* ```
*/
export function unzipWith<T, TResult>(
array: readonly T[][],
iteratee: (...values: T[]) => TResult
): TResult[] {
if (array.length === 0) {
return [];
}
const maxLength = Math.max(...array.map((arr) => arr.length));
const result: TResult[] = [];
for (let i = 0; i < maxLength; i++) {
const values = array.map((arr) => arr[i]);
result.push(iteratee(...values));
}
return result;
}
Example
import { unzipWith } from '@tulx/utils';
const zipped = zip([1, 2], [10, 20], [100, 200]);
unzipWith(zipped, (...args) => args.reduce((a, b) => a + b, 0));
// [111, 222]Related Functions
chunk
Creates an array of elements split into groups the length of size. If array can't be split evenly, the final chunk will be the remaining elements.
compact
Creates an array with all falsy values removed. The values false, null, 0, "", undefined, and NaN are falsy.
concat
Creates a new array concatenating array with any additional arrays and/or values.
difference
Creates an array of array values not included in the other given arrays. The order and references of result values are determined by the first array.
differenceBy
This method is like difference except that it accepts iteratee which is invoked for each element of array and values to generate the criterion by which they're compared.
differenceWith
This method is like difference except that it accepts comparator which is invoked to compare elements of array to values.