CyrefJS
CCyrefJS
فا
Back to documentation
Array/Since 1.38.0

zip

Combines two arrays element by element into an array of pairs, stopping when the shorter array is exhausted.

zip(array1, array2):[T, U][]

Parameters

array1T[]required

The first array whose elements will be paired with elements from the second array.

array2U[]required

The second array whose elements will be paired with elements from the first array.

Returns

[T, U][]

A new array containing pairs of corresponding elements from both input arrays. The result length is equal to the length of the shorter input array.

Examples

01

Basic usage

Combine two arrays element by element into pairs.

TypeScript
import { zip } from "@cyref/js";

const numbers = [1, 2, 3];
const letters = ["a", "b", "c"];

const result = zip(numbers, letters);

console.log(result);
// [[1, "a"], [2, "b"], [3, "c"]]
02

Different array lengths

When the arrays have different lengths, zip stops when the shorter array is exhausted.

TypeScript
import { zip } from "@cyref/js";

const numbers = [1, 2, 3, 4];
const letters = ["a", "b"];

const result = zip(numbers, letters);

console.log(result);
// [[1, "a"], [2, "b"]]
03

Different types

The two arrays can contain different types of values.

TypeScript
import { zip } from "@cyref/js";

const names = ["Alice", "Bob", "Charlie"];
const ages = [25, 30, 35];

const result = zip(names, ages);

console.log(result);
// [["Alice", 25], ["Bob", 30], ["Charlie", 35]]
04

Empty arrays

If either input array is empty, the result is an empty array.

TypeScript
import { zip } from "@cyref/js";

const numbers = [1, 2, 3];
const letters: string[] = [];

const result = zip(numbers, letters);

console.log(result);
// []
05

Objects

zip can also pair arrays containing objects and primitive values.

TypeScript
import { zip } from "@cyref/js";

const users = [
  { id: 1, name: "Alice" },
  { id: 2, name: "Bob" },
];

const roles = ["admin", "user"];

const result = zip(users, roles);

console.log(result);
// [
//   [{ id: 1, name: "Alice" }, "admin"],
//   [{ id: 2, name: "Bob" }, "user"],
// ]
Built with@cyref/js·Official documentation