Flattening an 'n-level' nested array in javascript

Input:

const input = [1, 2, [3, 4], 5, [[[6, 7], 8, [[[[9]]]]]], 10, 11, [12]]

Expected Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

What's flattening of arrays in javascript?

Flattening an array in JavaScript refers to the process of transforming a multi-dimensional array into a one-dimensional array by combining all its elements. This can be achieved using various techniques such as using nested loops or using built-in methods like the flat() method.

Below is an example code to flatten an array using the flat() method:

const flattenedArray = input.flat(Infinity);

console.log(flattenedArray); // Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

In the example code above, the flat() method is used to flatten the input. The parameter Infinity is passed to the method to flatten the array recursively to any depth.

Let's also take a look at a few other ways to achieve the same:

Using reduce() method:

function flattenArray(arr) {
  return arr.reduce(function (flat, toFlatten) {
    return flat.concat(
      Array.isArray(toFlatten) ? flattenArray(toFlatten) : toFlatten
    );
  }, []);
}
const flattenedArray = flattenArray(input);
console.log(flattenedArray); // Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

Using Array.prototype.concat() method:

function flattenArray(arr) {
  return [].concat.apply(
    [],
    arr.map(function (elem) {
      return Array.isArray(elem) ? flattenArray(elem) : elem;
    })
  );
}
const flattenedArray = flattenArray(input);
console.log(flattenedArray); // Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

Using only ES5 methods and without spread operator:

function flattenArray(arr) {
  const flattened = [];

  function flatten(element) {
    if (Array.isArray(element)) {
      element.forEach(flatten);
    } else {
      flattened.push(element);
    }
  }

  arr.forEach(flatten);
  return flattened;
}

const flattenedArray = flattenArray(input);
console.log(flattenedArray); // Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

Cool, we have now seen multiple ways to achieve flattening of arrays. Let's also take some time to understand some of the common use cases where it is quite helpful.

Common use cases of flattening of arrays

  1. Data processing: When processing data in the form of multi-dimensional arrays, flattening an array can make it easier to perform operations on it.

  2. DOM manipulation: Flattening arrays can also be useful when manipulating the Document Object Model (DOM) in web development.

  3. Image processing: In image processing, arrays can be used to represent images. Flattening these arrays can make it easier to perform operations on them.

  4. Machine learning: When dealing with large datasets in machine learning, flattening arrays can make it easier to perform operations on the data.

  5. File system navigation: In file system navigation, arrays can be used to represent directory structures. Flattening these arrays can make it easier to navigate through the directories.

I hope this article was helpful to you. If yes, please make sure to read my other articles. I am currently writing a series on common "Frontend engineering interview questions" based on my experience interviewing people at Amazon, RedHat, VMware, and Snapdeal, ...

Please subscribe to the newsletter to get the articles delivered directly to your mailbox.

Cheers

Arunkumar Sri Sailapathi.

#2Articles1Week