DEV Community

Cover image for How to flatten a nested array in Javascript
Adesile Emmanuel
Adesile Emmanuel

Posted on

How to flatten a nested array in Javascript

Today, I'll show you two ways to flaten a nested array regardless of how deeply nested it is.

1. Using Array flat method

function flatten(arr) {
  return arr.flat(Infinity)
}

const numArr = [1, [2, [3], 4, [5, 6, [7]]]];

flatten(numArr) // [1, 2, 3, 4, 5, 6, 7]
Enter fullscreen mode Exit fullscreen mode

2. Using Recursion and Reduce

function flatten(arr) {
  const newArr = arr.reduce((acc, item) => {
    if (Array.isArray(item)) {
      acc = acc.concat(flatten(item));
    } else {
     acc.push(item);
    }

    return acc;
  }, []);

  return newArr;
}

const numArr = [1, [2, [3], 4, [5, 6, [7]]]];

flatten(numArr) // [1, 2, 3, 4, 5, 6, 7]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)