DEV Community

DPC
DPC

Posted on

Daily JavaScript Challenge #JS-243: Flatten Nested Arrays

Daily JavaScript Challenge: Flatten 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

Given a nested array, implement a function to flatten it so that all sub-elements are lifted to the top level. For example, converting [[1, 2, [3]], 4] to [1, 2, 3, 4].

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

Top comments (2)

Collapse
 
maxart2501 profile image
Massimo Artizzu

It's trivial since the introduction of Array.prototype.flat, but once you have to create your own helper or rely on libraries like lodash.

This is a simple recursive solution - using ES2018 syntax only (i.e. when browsers started supporing .flat()):

function flatten(array) {
  const result = [];
  for (const item of array) {
    if (Array.isArray(item)) {
      result.push(...flatten(item));
    } else result.push(item);
  }
  return result;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
alan_weber_a9bc015e2f4c80 profile image
Alan Weber

const flat = nested.flat(Infinity);