Home > Software design >  Creating a function called zip() in Javascript
Creating a function called zip() in Javascript

Time:10-31

Part of an exercise I am to create a function called zip. It takes two arrays of equal length of elements and then separates them in two arrays with elements of equal indexes. I know there are other solutions using the map function but I am trying to figure out if there is another solution for this. So far I have this:

function zip(arr1, arr2) {
       let pairArr = [];
             for(var i = 0; i < arr1.length; i  ){
                 if (arr1.length === arr2.length){
                     let pairs = [arr1[i],arr2[i]];
                     pairArr.push(pairs);
                    } return pairArr;
             }
     }

This returns just one array with the first indexes of two arrays. [1, 2, 3, 4] [1, 2, 3, 4] returns [1, 1]. I need it to return [1, 1] [2, 2] [3, 3] [4, 4].
Thank you.

CodePudding user response:

You are putting the return inside the loop. You should add it outside the loop. For example:

function zip(arr1, arr2) {
       let pairArr = [];
             for(var i = 0; i < arr1.length; i  ){
                 if (arr1.length === arr2.length){
                     let pairs = [arr1[i],arr2[i]];
                     pairArr.push(pairs);
                    } 
             }
             return pairArr;
     }
     
     
     
console.log(zip([1, 2, 3, 4], [1, 2, 3, 4] ));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Thank you everyone your input. I didn't realize that I had my return in the loop. I did solve it. This is what I have for the zip function.

function zip(arr1, arr2) {
        let pairArr = [];
            for(var i = 0; i < arr1.length; i  ){
                if (arr1.length === arr2.length){
                    pairArr[i] = [arr1[i],arr2[i]];


                }
            }return pairArr;
    }

CodePudding user response:

Here is a better implementation of python-style zip in JavaScript, which can take an arbitrary number of arrays as arguments and returns a result as long as the shortest parameter.

const zip = (...arrays) => {
    const length = Math.min(...arrays.map(a => a.length));
    return [...Array(length).keys()].map(i => arrays.map(a => a[i]));
}
  • Related