Skip to content

zip

Compress multiple arrays into one array.

Basic Usage

typescript
import { zip } from 'radash'

const names = ['Alice', 'Bob', 'Charlie']
const ages = [25, 30, 35]
const cities = ['Beijing', 'Shanghai', 'Guangzhou']

const zipped = zip(names, ages, cities)
// [
//   ['Alice', 25, 'Beijing'],
//   ['Bob', 30, 'Shanghai'],
//   ['Charlie', 35, 'Guangzhou']
// ]

Syntax

typescript
function zip<T extends readonly unknown[]>(
  ...arrays: T
): Array<{ [K in keyof T]: T[K] extends readonly (infer U)[] ? U : never }>

Parameters

  • ...arrays (T): Arrays to combine, can pass any number of arrays

Return Value

Returns an array where each element is a tuple composed of elements from corresponding positions in the input arrays.

Examples

Basic Combination

typescript
import { zip } from 'radash'

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

const zipped = zip(letters, numbers)
// [
//   ['a', 1],
//   ['b', 2],
//   ['c', 3]
// ]

Combine Three Arrays

typescript
import { zip } from 'radash'

const fruits = ['apple', 'banana', 'cherry']
const colors = ['red', 'yellow', 'red']
const prices = [1.5, 2.0, 3.0]

const zipped = zip(fruits, colors, prices)
// [
//   ['apple', 'red', 1.5],
//   ['banana', 'yellow', 2.0],
//   ['cherry', 'red', 3.0]
// ]

Handle Arrays of Different Lengths

typescript
import { zip } from 'radash'

const short = [1, 2]
const long = ['a', 'b', 'c', 'd']

const zipped = zip(short, long)
// [
//   [1, 'a'],
//   [2, 'b']
// ] (based on the length of the shortest array)

Combine Object Arrays

typescript
import { zip } from 'radash'

const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Charlie' }
]

const scores = [85, 92, 78]

const zipped = zip(users, scores)
// [
//   [{ id: 1, name: 'Alice' }, 85],
//   [{ id: 2, name: 'Bob' }, 92],
//   [{ id: 3, name: 'Charlie' }, 78]
// ]

Create Key-Value Pairs

typescript
import { zip } from 'radash'

const keys = ['name', 'age', 'city']
const values = ['Alice', 25, 'Beijing']

const zipped = zip(keys, values)
// [
//   ['name', 'Alice'],
//   ['age', 25],
//   ['city', 'Beijing']
// ]

// Convert to object
const obj = Object.fromEntries(zipped)
// { name: 'Alice', age: 25, city: 'Beijing' }

Handle Mixed Types

typescript
import { zip } from 'radash'

const strings = ['hello', 'world']
const numbers = [1, 2]
const booleans = [true, false]
const objects = [{ key: 'value' }, { key: 'value2' }]

const zipped = zip(strings, numbers, booleans, objects)
// [
//   ['hello', 1, true, { key: 'value' }],
//   ['world', 2, false, { key: 'value2' }]
// ]

Using in Data Processing

typescript
import { zip } from 'radash'

interface DataPoint {
  timestamp: number
  value: number
  label: string
}

function processTimeSeriesData(timestamps: number[], values: number[], labels: string[]): DataPoint[] {
  const zipped = zip(timestamps, values, labels)
  
  return zipped.map(([timestamp, value, label]) => ({
    timestamp,
    value,
    label
  }))
}

const timestamps = [1000, 2000, 3000]
const values = [10, 20, 30]
const labels = ['point1', 'point2', 'point3']

const dataPoints = processTimeSeriesData(timestamps, values, labels)
console.log(dataPoints)
// [
//   { timestamp: 1000, value: 10, label: 'point1' },
//   { timestamp: 2000, value: 20, label: 'point2' },
//   { timestamp: 3000, value: 30, label: 'point3' }
// ]

Create Table Data

typescript
import { zip } from 'radash'

function createTable(headers: string[], ...columns: any[][]) {
  const zipped = zip(...columns)
  
  return {
    headers,
    rows: zipped
  }
}

const headers = ['Name', 'Age', 'City']
const names = ['Alice', 'Bob', 'Charlie']
const ages = [25, 30, 35]
const cities = ['Beijing', 'Shanghai', 'Guangzhou']

const table = createTable(headers, names, ages, cities)
console.log(table)
// {
//   headers: ['Name', 'Age', 'City'],
//   rows: [
//     ['Alice', 25, 'Beijing'],
//     ['Bob', 30, 'Shanghai'],
//     ['Charlie', 35, 'Guangzhou']
//   ]
// }

Process Form Data

typescript
import { zip } from 'radash'

function processFormData(fieldNames: string[], fieldValues: any[]) {
  const zipped = zip(fieldNames, fieldValues)
  
  return zipped.reduce((formData, [name, value]) => {
    formData[name] = value
    return formData
  }, {} as Record<string, any>)
}

const fieldNames = ['name', 'email', 'age', 'city']
const fieldValues = ['John Doe', 'john@example.com', 30, 'New York']

const formData = processFormData(fieldNames, fieldValues)
console.log(formData)
// {
//   name: 'John Doe',
//   email: 'john@example.com',
//   age: 30,
//   city: 'New York'
// }

Create Coordinate Points

typescript
import { zip } from 'radash'

function createPoints(xCoords: number[], yCoords: number[]) {
  const zipped = zip(xCoords, yCoords)
  
  return zipped.map(([x, y], index) => ({
    id: index + 1,
    x,
    y
  }))
}

const xCoords = [1, 2, 3, 4, 5]
const yCoords = [2, 4, 6, 8, 10]

const points = createPoints(xCoords, yCoords)
console.log(points)
// [
//   { id: 1, x: 1, y: 2 },
//   { id: 2, x: 2, y: 4 },
//   { id: 3, x: 3, y: 6 },
//   { id: 4, x: 4, y: 8 },
//   { id: 5, x: 5, y: 10 }
// ]

Process API Responses

typescript
import { zip } from 'radash'

interface ApiResponse {
  ids: number[]
  names: string[]
  emails: string[]
}

function processApiResponse(response: ApiResponse) {
  const { ids, names, emails } = response
  const zipped = zip(ids, names, emails)
  
  return zipped.map(([id, name, email]) => ({
    id,
    name,
    email
  }))
}

const apiResponse: ApiResponse = {
  ids: [1, 2, 3],
  names: ['Alice', 'Bob', 'Charlie'],
  emails: ['alice@example.com', 'bob@example.com', 'charlie@example.com']
}

const users = processApiResponse(apiResponse)
console.log(users)
// [
//   { id: 1, name: 'Alice', email: 'alice@example.com' },
//   { id: 2, name: 'Bob', email: 'bob@example.com' },
//   { id: 3, name: 'Charlie', email: 'charlie@example.com' }
// ]

Create Enum Mapping

typescript
import { zip } from 'radash'

function createEnumMap(keys: string[], values: any[]) {
  const zipped = zip(keys, values)
  
  return zipped.reduce((enumMap, [key, value]) => {
    enumMap[key] = value
    return enumMap
  }, {} as Record<string, any>)
}

const statusKeys = ['PENDING', 'ACTIVE', 'INACTIVE', 'DELETED']
const statusValues = [0, 1, 2, 3]

const statusEnum = createEnumMap(statusKeys, statusValues)
console.log(statusEnum)
// {
//   PENDING: 0,
//   ACTIVE: 1,
//   INACTIVE: 2,
//   DELETED: 3
// }

Process CSV Data

typescript
import { zip } from 'radash'

function parseCSV(csvString: string) {
  const lines = csvString.trim().split('\n')
  const headers = lines[0].split(',')
  const dataLines = lines.slice(1)
  
  const columns = headers.map((_, columnIndex) =>
    dataLines.map(line => line.split(',')[columnIndex])
  
  const zipped = zip(...columns)
  
  return zipped.map(row => {
    const obj: Record<string, string> = {}
    headers.forEach((header, index) => {
      obj[header] = row[index]
    })
    return obj
  })
}

const csvData = `name,age,city
Alice,25,Beijing
Bob,30,Shanghai
Charlie,35,Guangzhou`

const parsed = parseCSV(csvData)
console.log(parsed)
// [
//   { name: 'Alice', age: '25', city: 'Beijing' },
//   { name: 'Bob', age: '30', city: 'Shanghai' },
//   { name: 'Charlie', age: '35', city: 'Guangzhou' }
// ]

Notes

  1. Length handling: Based on the length of the shortest array, excess parts are ignored
  2. Keep original arrays unchanged: zip does not modify the original arrays, but returns a new array
  3. Type safety: The returned array type is inferred based on the input array types
  4. Performance: Time complexity is O(n), where n is the length of the shortest array
  5. Empty arrays: If any input array is empty, returns an empty array

Differences from Other Methods

  • map(): Can only process a single array
  • zip(): Can process multiple arrays simultaneously
  • Array.from(): Requires manually creating index mappings
  • Object.fromEntries(): Can only create key-value pairs, while zip is more flexible

Practical Application Scenarios

  1. Data processing: Combine data from multiple sources
  2. Table creation: Convert column data to row data
  3. Coordinate processing: Combine x and y coordinates
  4. Form processing: Pair field names with values
  5. API processing: Handle separated array responses

Released under the MIT License.