zipWith
arrays
This method is like zip except that it accepts iteratee to specify how grouped values should be combined.
Installation
Import
import { zipWith } from '@tulx/utils';Source Code
Implementation
/**
* This method is like zip except that it accepts iteratee to specify how grouped values should be combined.
*
* @param arrays - The arrays to process.
* @param iteratee - The function to combine grouped values.
* @returns The new array of grouped elements.
*
* @example
* ```ts
* zipWith([1, 2], [10, 20], [100, 200], (a, b, c) => a + b + c);
* // [111, 222]
* ```
*/
export function zipWith<TResult>(...args: readonly unknown[]): TResult[] {
if (args.length < 2) {
return [];
}
const iteratee = args[args.length - 1] as (...values: unknown[]) => TResult;
const arrays = args.slice(0, -1) as readonly unknown[][];
if (arrays.length === 0) {
return [];
}
const maxLength = Math.max(...arrays.map((arr) => arr.length));
const result: TResult[] = [];
for (let i = 0; i < maxLength; i++) {
const values = arrays.map((arr) => arr[i]);
result.push(iteratee(...values));
}
return result;
}
Example
import { zipWith } from '@tulx/utils';
zipWith([1, 2], [10, 20], [100, 200], (a, b, c) => a + b + c);
// [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.