DEV Community

DPC
DPC

Posted on

5 4 4 3 5

Daily JavaScript Challenge #JS-155: Flatten Deeply Nested Arrays

Daily JavaScript Challenge: Flatten Deeply Nested Arrays

Hey fellow developers! πŸ‘‹ Welcome to today's JavaScript coding challenge. Let's keep those programming skills sharp!

The Challenge

Difficulty: Medium

Topic: Array Manipulation

Description

Write a function that takes a deeply nested array of integers and returns a completely flattened array. The nested arrays can have any depth.

Ready to Begin?

https://www.dpcdev.com/

  1. Fork this challenge
  2. Write your solution
  3. Test it against the provided test cases
  4. Share your approach in the comments below!

Want to Learn More?

Check out the documentation about this topic here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray

Join the Discussion!

  • How did you approach this problem?
  • Did you find any interesting edge cases?
  • What was your biggest learning from this challenge?

Let's learn together! Drop your thoughts and questions in the comments below. πŸ‘‡


This is part of our Daily JavaScript Challenge series. Follow me for daily programming challenges and let's grow together! πŸš€

javascript #programming #coding #dailycodingchallenge #webdev

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly β€” using the tools and languages you already love!

Learn More

Top comments (1)

Collapse
 
maxart2501 profile image
Massimo Artizzu β€’
const flatten = array => array.flat(Infinity);
Enter fullscreen mode Exit fullscreen mode

Jokes aside... The easiest one would be recursive:

const flatten = array => {
  const flattened = [];
  for (const item of array) {
    if (Array.isArray(item)) {
      for (const subitem of flatten(item)) {
        flattened.push(subitem);
      }
    } else flattened.push(item);
  }
  return flattened;
};
Enter fullscreen mode Exit fullscreen mode

Next step: instead of Array.isArray, use this:

const isIterable = item => !!item && Symbol.iterator in item;
Enter fullscreen mode Exit fullscreen mode

Some comments may only be visible to logged-in visitors. Sign in to view all comments.

Neon image

Next.js applications: Set up a Neon project in seconds

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 β†’