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

178
Vistas
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 Respuestas
Responde la pregunta

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 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