zipWith()
zipWith<
T,R>(arrays,iteratee):R[]
Creates an array of grouped elements, applying a function to each group.
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+)"]