Javascript . NET Zip() method

Asked

Viewed 99 times

7

I was reading that question and I noticed there’s no method Zip in Javascript, I would like to know how to implement a method that works the same way or if there is some other function that does the same job without using any external lib.

2 answers

6


It doesn’t have ready anyway, but in the background it is only to map, what many already do.

It seems to me that something like this solves most cases, but these algorithms can be complicated in extreme cases, the simple way:

var array1 = [1, 2, 3];
var array2 = [4, 5, 6];
console.log(array1.map((value, i) => value * array2[i]));

I put in the Github for future reference.

Obviously you can create a function called zip() and encapsulate this logic giving more semantics to what you want, and then you can even put in a prototype to be available to any array and so you can call for the object, and obviously, you can go on sophisticating and generalizing as you need it.

To understand more about zip.

3

A solution would be to create a function that receives an array and the function that is applied to the elements. You can add in prototype of Array to make it available to any array:

Array.prototype.zip = function(v, func) {
    let len = Math.min(this.length, v.length); // pegar o tamanho do menor array
    let result = [];
    for (let i = 0; i < len; i++) {
        // chamar a função passando os elementos de cada um dos arrays
        result.push(func(this[i], v[i]));
    }
    return result;
}

let numbers = [1, 2, 3, 4];
let words = ['one', 'two', 'three'];

let v = numbers.zip(words, (a, b) => `${a} - ${b}`);
v.forEach(s => console.log(s));

I put a condition to consider the size of the smallest array, if they have different sizes, because according to the documentation, that’s what he does:

If the sequences do not have the same number of Elements, the method merges sequences until it Reaches the end of one of them. For example, if one Sequence has three Elements and the other one has four, the result Sequence will have only three Elements

That is, if one array has size 3 and the other 4, the fourth element of the largest array is ignored, and the returned array will have only 3 elements.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.