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)

Neon image

Set up a Neon project in seconds and connect from a Node.js application

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

👋 Kindness is contagious

Explore this insightful write-up embraced by the inclusive DEV Community. Tech enthusiasts of all skill levels can contribute insights and expand our shared knowledge.

Spreading a simple "thank you" uplifts creators—let them know your thoughts in the discussion below!

At DEV, collaborative learning fuels growth and forges stronger connections. If this piece resonated with you, a brief note of thanks goes a long way.

Okay