zip
Zips arrays together in the form of an array of arrays.
1./**2.* Zips arrays together in the form of an array of arrays.3.**/4.type Args<T extends Array<Array<unknown>>> = {5.arr: T;6.strict?: boolean;7.};8.9.const zip = <T extends Array<Array<unknown>>>({10.arr,11.strict = false,12.}: Args<T>): T => {13.const maxIndex = arr.map((a) => a.length).reduce((a, b) => Math.max(a, b), 0);14.const minIndex = arr15..map((a) => a.length)16..reduce((a, b) => Math.min(a, b), maxIndex);17.18.let result = [] as unknown[][];19.20.const upto = strict ? minIndex : maxIndex;21.22.for (let i = 0; i < upto; i++) {23.const zip = arr.map((a) => a[i]);24.result.push(zip);25.}26.27.return result as T;28.};29.30.export default zip;
1. Installtion
npx @jrtilak/lazykit add zip
2. Parameters
-
arr
(T
)
An array of arrays to be zipped together. Each inner array represents a collection of elements that will be combined based on their indices. -
strict
(optional) (boolean
)
A flag that determines whether to limit the zipping process to the shortest array's length. If set totrue
, only the elements up to the shortest array's length will be included in the result. Defaults tofalse
.
3. Returns
T
Returns a new array of arrays, where each inner array contains the elements from the input arrays at the corresponding indices. Ifstrict
is true, only elements up to the length of the shortest array will be included.
4. Type Parameters
T
The type of the input array of arrays. This allows the function to work with nested arrays of any type, ensuring type safety for the zipped elements.
5. Usage
1. Zipping Two Arrays with Default Behavior
1.import zip from '@/helpers/zip';2.3.const arrays = [[1, 2, 3], ["a", "b", "c", "d"]];4.const result = zip({ arr: arrays });5.6.console.log(result);7.// Output: [[1, "a"], [2, "b"], [3, "c"], [undefined, "d"]]
2. Strict Zipping Based on Minimum Array Length
1.import zip from '@/helpers/zip';2.3.const arrays = [[1, 2, 3], ["x", "y"]];4.const strictResult = zip({ arr: arrays, strict: true });5.6.console.log(strictResult);7.// Output: [[1, "x"], [2, "y"]]
3. Zipping Three Arrays with Default Behavior
1.import zip from '@/helpers/zip';2.3.const arrays = [[1, 2, 3], ["a", "b", "c", "d"], [true, false]];4.const result = zip({ arr: arrays });5.6.console.log(result);7.// Output: [[1, "a", true], [2, "b", false], [3, "c", undefined], [undefined, "d", undefined]]
4. Strict Zipping with Three Arrays (Minimum Length)
1.import zip from '@/helpers/zip';2.3.const arrays = [[1, 2, 3], ["x", "y", "z"], [10, 20]];4.const strictResult = zip({ arr: arrays, strict: true });5.6.console.log(strictResult);7.// Output: [[1, "x", 10], [2, "y", 20]]