Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

169
Views
Creating a function called zip() in Javascript

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.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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] ));

about 4 years ago · Juan Pablo Isaza Report

0

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;
    }
about 4 years ago · Juan Pablo Isaza Report

0

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]));
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!