Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

170
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda