Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

180
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!