I’m just curious why there isn’t any built-in zip
function in javascript.
I’ve used a number of modern or older programming languages, such as python, kotlin, and rust. These days I’m writing codes in javascript and enjoying functional programming with it, since it provides built-in higher order functions such as filter
, map
, and reduce
. At the same time it seems that the javascript community encourages functional programming.
However, I encountered a question: Why javascript does not provide zip
function?
It is provided in many other programming languages and very useful and convenient when I need to work with multiple iterables in parallel. For example, in python:
numbers = [1, 2, 3]
upper = ["A", "B", "C"]
lower = ["a", "b", "c"]
for n, u, l in zip(numbers, upper, lower):
print(f"{n}, {u}, {l}")
Of course the same result can be achieved in javascript, using map
or forEach
, or for loop.
const numbers = [1, 2, 3];
const upper = ["A", "B", "C"];
const lower = ["a", "b", "c"];
numbers.forEach((n, i) => {
console.log(`${n}, ${upper[i]}, ${lower[i]}`);
});
It doesn’t look so neat for me, so I may write a custom zip function.
(btw, it won’t work correctly when iterables of different sizes are provided.)
function zip(...iterables) {
return iterables[0].map((_, i) => iterables.map((it) => it[i]));
}
zip(numbers, upper, lower).forEach(([n, u, l]) => {
console.log(`${n}, ${u}, ${l}`);
})
But I don’t want to write this everytime.
Neither to add any library for it.
So what’s the reason there’s no built-in one?