zip
Zips arrays together in the form of an array of arrays.
1. Code
type Args = {
arr: any[][];
strict?: boolean;
};
/**
* Zips multiple arrays into a single array of tuples.
*
* @template T - The type of elements in the arrays.
* @param {Args<any>} options - The options for zipping the arrays.
* @param {any[][]} options.arr - The arrays to be zipped.
* @param {boolean} [options.strict=false] - Indicates whether to zip strictly based on the minimum length of the arrays.
* @returns {any[][]} - The zipped array of tuples.
*/
const zip = ({ arr, strict = false }: Args): any[][] => {
const maxIndex = arr.map((a) => a.length).reduce((a, b) => Math.max(a, b), 0);
const minIndex = arr
.map((a) => a.length)
.reduce((a, b) => Math.min(a, b), maxIndex);
const result: any[][] = [];
const upto = strict ? minIndex : maxIndex;
for (let i = 0; i < upto; i++) {
const zip = arr.map((a) => a[i]);
result.push(zip);
}
return result;
};
export default zip;
2. Installation
npx @jrtilak/lazykit@latest add zip
3. Description
The zip
function in the combines multiple arrays into a single array of tuples.
The function accepts an object
as an argument, which has two properties: arr
(an array of arrays) and strict
(a boolean). The strict property is optional and defaults to false if not provided.
If the strict property is set to true, the function will only zip arrays of the same length. If the strict property is set to false, the function will zip arrays of different lengths by filling in the missing values with undefined
.
This function is useful for combining multiple arrays into a single array of tuples.
4. Props
Prop
Type
Default Value
arr*array[]---
strictbooleanfalse
5. Examples
import zip from ".";
const arr = [
[1, 2, 3],
["a", "b"],
];
const result = zip({ arr });
console.log(result);
// Expected output: [[1, "a"], [2, "b"], [3, undefined]]
// strict mode
const resultStrict = zip({ arr, strict: true });
console.log(resultStrict);
// Expected output: [[1, "a"], [2, "b"]]