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
flattening an array of arrays into a single array that has all the elements of the original arrays 'by recursion'

I have done it by reduce but I wanna do it by recursion and console prints error TypeError: arr[0].concat is not a function

let arrays = [[1, 2, 3], [4, 5], [6]];
// Your code here.
// → [1, 2, 3, 4, 5, 6]

let arr = arrays.reduce((acc, current, Index, arr) => {
  return acc.concat(current);
}, []);
console.log(arr);

function flattening(arr) {
  if (arr.length <= 1) return arr;
  else return flattening(arr[0].concat(arr[1]));
}
console.log(flattening(arrays));
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Concat the first element of the array outside of the call to flattening, and then you can pass the rest of the subarrays to flattening. Keep the function signature of flattening the same wherever it's called - its argument should accept an array of arrays (but flattening(arr[0].concat(arr[1])) results in passing in only a flat array, which isn't right).

const arrays = [[1, 2, 3], [4, 5], [6]];
function flattening(arr) {
  if (arr.length < 1) return [];
  else return arr[0].concat(flattening(arr.slice(1)));
}
console.log(flattening(arrays));

or

const arrays = [[1, 2, 3], [4, 5], [6]];
function flattening([arr1, ...rest]) {
  return !rest.length
    ? arr1
    : arr1.concat(flattening(rest));
}
console.log(flattening(arrays));

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