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

181
Visualizações
Node - Merge dynamic amount of arrays together - alternate the items in the result array

I have a bunch of arrays of different length holding objects of the same types. What I want is to merge all these arrays into one final array. The issue I have is that the items need to alternate in the final result array.

so if for example one array only holds one value to altenate the results until there is no element in the shortest length array and continue with just the others still holding values.

const arr1 = [arr1Obj, arr1Obj, arr1Obj]
const arr2 = [arr2Obj, arr2Obj, arr2Obj]
const arr3 = [arr3obj]

//no pre-defined amount of arrays, could be only one array or 10+

//output desired
[arr1Obj, arr2Obj, arr3Obj, arr1Obj, arr2Obj, arr1Obj, arr2Obj]

My approach was just using a bunch of nested for-loops which I am sure is not the best way of doing this. I am wondering, how would the shortest most performant es6 way look alike? Preferably without using modules like lodash.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

We can use Array.from() and Array.reduce() to get the sequence we wish for.

We start by getting the max array length using Math.max(), then we use Array.from() to create our output array, using Array.reduce() to append each element as we iterate over the arrays, flattening at the end:

const arr1 = ['arr1Obj', 'arr1Obj', 'arr1Obj']
const arr2 = ['arr2Obj', 'arr2Obj', 'arr2Obj']
const arr3 = ['arr3Obj']

// Sort our input by length, we want the longest array first...
const arrays = [arr1, arr2, arr3]; 

const maxLength = Math.max(...arrays.map(a => a.length));

const result = Array.from({ length: maxLength }, (v, idx) => arrays.reduce((acc, arr) => {
    if (idx < arr.length) {
        acc.push(arr[idx]);
    }
    return acc;
}, [])).flat();

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Relatório

0

You can use .reduce to n arrays with the jth elements and then .push all of their elements:

let arrs = [
    [1,2,3],
    [2,undefined,'4',6,90,3.14],
    [1,0,-1,5],
    [],
    [100, 300, -Infinity]
];

let merged = [];
for (var i = 0, j = 0; i < arrs.length; i++, j++) {
  merged.push(...arrs.reduce((a, c) => {
   if (c.length > j) a.push(c[j]);
   return a;
  }, []));
}
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