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

109
Visualizações
I am trying to regroup an array of arrays using reduce... and failing

So, I am trying to regroup the elements... well in a way that is hard to explain. Here is a sample of input and expected output...

zip(['fred', 'barney'], [30, 40], [true, false]); 

should output...

→ [['fred', 30, true], ['barney', 40, false]]

I thought reduce would be appropriate since I am supposed to take multiple arrays and convert it into a single array that contains the same amount of arrays as the input array's length...

Here is what I am working on... It isn't functioning but I believe I am close to the right idea!

function zip(array) {
    return array.reduce((acc, next) => {
        // get length of next array to use in for-loop...
        let numOfElem = next.length
        // use a for loop to access different indexed arrays...
        for (let i = 0; i < numOfElem; i++) {
            // this is supposed to push the appropriate element in the next array to the accumulator array's corresponding index...
            acc[i].push(next[i]);
        }
        return acc;
    }, [])
}

const result = zip(['fred', 'barney'], [30, 40], [true, false]); 
console.log(result);

I believe I am attempting to push incorrectly? The idea behind acc[i].push(next[i]) is that acc[i] would create the necessary amount of arrays based off of the length of the input arrays. The code is non-functional. I am just looking for a way to get it working, even if by a different method!

Thanks for taking the time to read this and for any feedback, tips or tricks!

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

0

You could reduce the parameters and map the part result of the same index.

const
    zip = (...array) =>
        array.reduce((r, a) => a.map((v, i) => [...(r[i] || []), v]), []);

console.log(zip(['fred', 'barney'], [30, 40], [true, false]));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Approach for unequal lengths of arrays.

const
    zip = (...array) => array.reduce((r, a, i) => {
        while (r.length < a.length) r.push(Array(i).fill(undefined));
        return r.map((b, j) => [...b, a[j]]);
    }, []);

console.log(zip(['fred', 'barney'], [30, 40, 3, 4, 5, 6, 7], [true, false, 'don\'t know']));
.as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Relatório

0

Something like this?

const zip=(arr)=>{
    let res=[]
    arr[0].forEach((el,k) => {
        res.push(arr.reduce((acc, curr)=>{
            acc.push(curr[k])
            return acc
        },[]))  
    });
  return res
}
console.log(zip([['moe', 'larry', 'curly'], [30, 40, 50], [true]]))

about 4 years ago · Juan Pablo Isaza Relatório

0

function zip(...arrays) {
  const flattened = arrays.flatMap(item => item)
  const result = []
  for (let index = 0; index <= arrays.length; index++) {
    result[index] = []
    for (let step = index; step < flattened.length; step = step + arrays[0].length) {
      result[index][(step - index) / arrays[0].length] = flattened[step]
    }
  }
  return result
}

const arr1 = [ 'fred', 'barney', 'alpha', 'beta' ]
const arr2 = [ 30, 40, 50, 60 ]
const arr3 = [ true, false, null, true ]

console.log(zip(arr1, arr2, arr3))

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