DEV Community

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

Posted on

5 1

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)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay