Aller au contenu principal

zipWith()

zipWith<T, R>(arrays, iteratee): R[]

Creates an array of grouped elements, applying a function to each group.

remarque

When arrays have unequal lengths, shorter arrays contribute undefined for missing indices.


Type Parameters

T: T

The type of elements in the arrays.

R: R

The type of the result.


Parameters

arrays: readonly (readonly T[])[]

The arrays to process.

iteratee: (...values) => R

The function to combine grouped values.


Returns: R[]

A new array of combined values.


Since

2.0.0


Performance

O(n × m) where n is the length of the longest array and m is the number of arrays.


Also known as

zip (Radashi) · zipWith (Lodash, es-toolkit, Remeda, Ramda, Effect) · ❌ (Modern Dash, Antfu)


Example

zipWith([[1, 2], [10, 20], [100, 200]], (a, b, c) => a + b + c);
// => [111, 222]

zipWith([[1, 2, 3], [4, 5, 6]], (a, b) => a * b);
// => [4, 10, 18]

How it works?

Combines arrays with a custom function instead of creating tuples.

Element-wise operation


Use Cases

Combine arrays with transformation 📌

Merge arrays while applying a function to each group. Perfect for calculations across parallel datasets.

const prices = [100, 200, 150];
const quantities = [2, 1, 3];

const totals = zipWith(prices, quantities, (price, qty) => price * qty);
// => [200, 200, 450]

Calculate differences between datasets

Compute element-wise differences or ratios. Useful for variance analysis or comparison metrics.

const actual = [100, 150, 200];
const expected = [120, 140, 180];

const variance = zipWith(actual, expected, (a, e) => a - e);
// => [-20, 10, 20]

const percentDiff = zipWith(
actual,
expected,
(a, e) => ((a - e) / e * 100).toFixed(1) + "%"
);
// => ["-16.7%", "7.1%", "11.1%"]

Combine with custom logic

Merge arrays using any transformation function. Essential for complex data merging or aggregation. Each utility is designed to solve specific array manipulation challenges in real-world development scenarios.

const names = ["Alice", "Bob"];
const scores = [95, 87];
const grades = ["A", "B+"];

const results = zipWith(
names,
scores,
grades,
(name, score, grade) => `${name}: ${score} (${grade})`
);
// => ["Alice: 95 (A)", "Bob: 87 (B+)"]