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

152
Vistas
JavaScript - Merge two arrays with different sizes

I have two arrays:

var array1= [1,3,5,7,9,11]
var array2= [undefined,4,6]

I need to merge one element of the array1, then one element of the array2, etc. This is my code:

function mergeArrays(array1, array2){
    var array3 = []; 
    maxlength = Math.max(array1.length, array2.length);

for(i=0;i<maxlength;i++){   
    array3.push(array1[i]);  
    array3.push(array2[i]);
}      
    return console.log(array3);
}

The output now is:

array3 = [1,undefined,3,4,6,7,undefined,9,undefined,11,undefined]

I need the output to be:

array3 = [1,undefined,3,4,6,7,8,11]

I mean, I can't use ( != undefined), because if I have an undefined in the middle of the array it has to be there.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You are not placing a check for the length of shorter array. Your function is fetching a value which is higher than the length of the array, hence, extra undefined. This should do the job

var array1 = [1, 3, 5, 7, 9, 11];
var array2 = [undefined, 4, 6];

function mergeArrays(array1, array2) {
  var array3 = [];
  maxlength = Math.max(array1.length, array2.length);

  for (i = 0; i < maxlength; i++) {
    if (i < array1.length) array3.push(array1[i]);
    if (i < array2.length) array3.push(array2[i]);
  }
  return console.log(array3);
}

mergeArrays(array1, array2);

about 4 years ago · Juan Pablo Isaza Denunciar

0

Instead of checking for undefined, you could check for the array lengths, like this:

const array1 = [1,3,5,7,9,11]
const array2 = [undefined,4,6]

function mergeArrays(array1, array2){
    const array3 = []; 
    const maxlength = Math.max(array1.length, array2.length);

    for(let i = 0; i < maxlength; i++) {
        if (i < array1.length) {
            array3.push(array1[i]);  
        }
        
        if (i < array2.length) {
            array3.push(array2[i]);
        }
    }
    
    return array3;
}

console.log(mergeArrays(array1, array2));

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can grab the max length of the two arrays and loop until you hit that value. While looping, check if the length has been exceeded and push onto the result.

const allEqual = (...args) =>
  ((head, ...tail) => tail.every(curr => curr === head))
  (args.map(v => JSON.stringify(v)));

const test = ({ actual, expected }) => {
  console.log(JSON.stringify(actual));
  console.log(allEqual(actual, expected));
};

const interlaceArrays = (...arrays) => {
  const result = [];
  const maxLen = Math.max(...arrays.map(({ length }) => length));
  for (let i = 0; i < maxLen; i++) {
    arrays.forEach(arr => {
      if (i < arr.length) result.push(arr[i]);
    })
  }
  return result;
};

const
  odd = [1, 3, 5, 7, 9, 11],
  even = [undefined, 4, 6],
  other = ['a', 'b'];

test({
  actual: interlaceArrays(odd, even),
  expected: [1, undefined, 3, 4, 5, 6, 7, 9, 11]
});

test({
  actual: interlaceArrays(odd, even, other),
  expected: [1, undefined, 'a', 3, 4, 'b', 5, 6, 7, 9, 11]
});
.as-console-wrapper { top: 0; max-height: 100% !important; }

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