20% discount for your first project

Get a Quote

Flatten array of Array

Flatten array of Array

Suboor Khan

#Problem solving#Javascript
Flatten array of Arrays without using flat prototype method

Flatten array of Arrays without using flat prototype method

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;
      }
    }
  };
};
HomeServicesCase StudiesHire Us