Flatten array of Array

Flatten array of Arrays without using flat prototype method

Suboor Khan
Suboor Khan

Suboor Khan

Software Engineer

Problem solvingJavascript

let nums = [[1, 2], [[3, 4]], [[[5], [6]]]];


/**
 * Using reduce method
 */
const flatten = (arr: any[]) =>
  arr.reduce((acc, val) => {
    Array.isArray(val) ? acc.push(...flatten(val)) : acc.push(val);
    return acc;
  }, []);


/**
 * Using recursive and thunk function
 */
const flatten2 = () => {
  const list = [];
  return function flat(arr) {
    for (let i = 0; i < arr.length; i++) {
      if (typeof arr[i] === 'number') {
        list.push(arr[i]);
      } else if (Array.isArray(arr[i])) {
        flat(arr[i]);
      }

      if (i === arr.length - 1) {
        return list;
      }
    }
  };
};
HomeNews feedsWorkSessionsContact