How to Flatten an Array?

December 30, 2022

☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee

Array flattening refers to transforming multi-dimensional arrays into one-dimensional arrays. Currently, there are many utility libraries in the JavaScript community provide this method. For example, the well-known lodash library has the flattenDeep method you could use to flatten arrays.

The actual example is as follows, no matter how many levels there are, it will be converted into a one-dimensional array after passing the array into flattenDeep:

let array = [1, 2, [3, [4, 5, [6, 7, [8]]]]];

function flattenDeep(arr) {
   ...
}

const flattenArray = flattenDeep(array);

console.log(flattenArray); // [1,2,3,4,5,6,7,8]

In the JavaScript interview, the question "If there is no ready-made library, how would you implement array flattening?" is frequently asked. If you don't know how to implement it yet, let's take a look together.

Approach 1: JavaScript built-in flat()

In fact, the easiest way to implement array flattening is through the JavaScript built-in method — Array.prototype.flat().

The flat() method will accept a parameter depth, which represents the dimension to be flattened. If no value is passed in, the default value will be 1, and this method will return a new array. It should be noted that the flat() method ignores spaces when flattening. You can see the following code:

// This array is a five-dimensional array
let array = [1, 2, , [3, [4, 5, [6, 7, [8]]]]];

// Depth is 2. Space will be removed. A 3-dimensional array will be returned as a result
console.log(array.flat(2)); // [1,2,3,4,5,[6, 7, [8]]

The above method seems very convenient, but if you don't know the depth, you won't be able to know what to pass in. So how do you do flattening without knowing how many dimensions the array is? In fact, you can pass Infinity as the depth, and it will always return a one-dimensional array no matter how many dimensions the original array has.

let array = [1, 2, [3, [4, 5, [6, 7, [8]]]]];

function flatten(arr) {
  return arr.flat(Infinity);
}

const flattenArray = flatten(array);
console.log(flattenArray); // [1,2,3,4,5,6,7,8]

Approach 2: Recursion

The interviewer may ask "How do you implement a flatten yourself if you don't use the JavaScript built-in method?". To do so, we can leverage the power of recursion. Check each item in the array through the for loop. If the item is an array, continue to call the flatten function; if it is not an array, then directly add it to the new array through the push method.

let array = [1, 2, [3, [4, 5, [6, 7, [8]]]]];

function flatten(arr, output = []) {
  for (const val of arr) {
    if (Array.isArray(val)) {
      flatten(val, output);
    } else {
      output.push(val);
    }
  }
  return output;
}

const flattenArray = flatten(array);
console.log(flattenArray); // [1,2,3,4,5,6,7,8]

Approach 3: Functional Programming with reduce

We can re-write approach 2 in a more functional programming style. To do so, we can use reduce to recurse each level of the array and form a new array. The logic of approach 3 and approach 2 is similar, except that in approach 3, it is simplified through reduce.

let array = [1, 2, [3, [4, 5, [6, 7, [8]]]]];

function flatten(arr) {
  return arr.reduce(
    (acc, cur) =>
      // Determine whether the cur is an array, if it is an array, it will recursively call flatten on the element
      // If it is not an array, just add it directly to the last bit of the new array
      Array.isArray(cur) ? [...acc, ...flatten(cur)] : [...acc, cur],
    []
  );
}

const flattenArray = flatten(array);
console.log(flattenArray); // [1,2,3,4,5,6,7,8]
☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee