Progressive Full Stack Application Development with Live Projects

JavaScript Lesson

Flatten Arrays in JavaScript

Flatten an Array in JavaScript

Arrays are the most funamental data structure in almost every programming language. They are used to store a collectiion of values in an indexed manner. Here is how a JavaScript array looks like.

// One Dimensional Array
const numbers = [2,4,6,8,10];

An array can hold any type of data, including other arrays. When an array contain other arrays, it results in nested arrays or multi-dimensional arrays.

Multi-Dimensional Arrays


A multi-dimensional array is an array with more than one level or dimension. For example, two-dimensional (2D) array, is an array of arrays, meaning it is a matrix of rows and columns (or just think of a table). A 3D array adds another dimension to a 2D array, turning it into an array of arrays of arrays. Simple Enough! Right.

// Two Dimensional Array
const data = [2,3,7, [9,12], 18];

// Three Dimensional Array
const arr = [1,2,3,[4,[5]],[6,[7,[8]],9],[10],11];

What is Array Flattening?


Multi-dimensional arrays are useful, but there are situations where we want to flatten the array, i.e., reduce the multi-dimensional array into a single-dimensional array. Let us have a look at the 3D array below:

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

The flattened array will look like this:

Expected : [1,2,3,4,5,6,7,8,9,10,11];

So now that we know what array flattening is. Let us write javascript programs to flatten some arrays having multiple levels of nesting.

1. Flattening Array using JavaScript’s Array.flat() method


Arrays in Java has an in-built flat() function that creates a new array by recursively concatenating the sub-arrays of the original array up to the given depth. The default depth is 1.

Example 1: Flattening an array with depth of 1

/** Flattening arrays having nesting up to 1 level **/

let nestedArray = [1, [2, 3], 4, 5, 6];
let flatArray = nestedArray.flat();
console.log(flatArray);

Example 2: Flattening an array with depth of 2

/** Flattening arrays having nesting up to 2 levels **/

let nestedArray = [1, [2, 3], [4, [5, 6, 7]], 8, 9];
let flatArray = nestedArray.flat(2);
console.log(flatArray);

2. Flattening any JavaScript Array (without using in-built functions)


Let us write a function that can take any array as input and returns the flattened array. We also want this function to handle multiple levels recursively without requiring to accept a level parameter.

Example 3: Flattening an array without using any in-built function

/** A function to flatten multi-level arrays **/

const flatten = (nested) => {
  const flat = [];
  const flattenArray = (array) => {
    let counter = 0
    while (counter < array.length) {
      const val = array[counter];
      if (Array.isArray(val)) {
        flattenArray(val);
      } else {
        flat.push(val)
      }
      counter++;
    }
  }
  flattenArray(nested);
  return flat;
}

/** Calling function with input array **/
const arr = [1,2,3,[4,[5]],[6,[7,[8]],9],[10],11];
const flatArray = flatten(arr);
console.log(flatArray);

Explaination:

  • flatten() is the function that takes an array input and defines a helper function flattenArray().
  • This inner function, flattenArray has access to variables of outer function i.e. flatten(), is designed to recursively iterate over the given array (array), flattening it as needed. The recursion allows the function to handle arrays of any depth. Hope you understand the Closure at Work.
  • An empty array flat is created. This array will iteratively hold all the flattened values (i.e., non-array elements from the nested array).
  • A variable counter is initialized to 0. It will be used as an index to loop through the array.
  • The while loop iterates through the input array and pushes its element into a new array.
  • If the next element of an array is a nested array, the function recursively calls itself to iterate for the items of nested array.
  • This continues until all the nested arrays have been pushed into the new array.