Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

147
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda