Home > database >  flattening an array of arrays into a single array that has all the elements of the original arrays &
flattening an array of arrays into a single array that has all the elements of the original arrays &

Time:08-08

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

CodePudding user response:

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

  • Related