Skip to main content

Command Palette

Search for a command to run...

Array Flatten in JavaScript

Updated
3 min read
Array Flatten in JavaScript

Array is the collection of elements in javascript. These elements can be basic data structure like number, string, etc and sometimes even array. This is the point where nested array and its operation comes into the picture. In this blog, we are going to deep dive in this concept.

What are nested arrays ?

Array containing one or more arrays in the form of elements are called nested arrays.

In other words, it is array inside array.

Example -

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

Why flattening arrays is useful ?

Array falttening means converting a nested array into a single level array.

Example

const array = [[1], [2, 3], [4, 5, 6], [7, [8, 9]]];
const finalArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];

This is useful because of the following reason which is mentioned below.

  1. Easier data processing

  2. simplifies complex data

  3. useful with API data

  4. Better for calculation

  5. Improves compatibility - Some functions or libraries expect flat arrays, not nested ones.


Concepts of flattening arrays

Flattening of array from nested array to single level array is done with the help of multiple steps.

  1. If an element is array then break it down.

  2. If it is a value then keep it.

  3. Keep it going upto k levels as mention or asked to do.

Example

let array = [[1], [2, [3, 4]], 5];
  • Step 1 - Take [1] and keep it.

  • Step 2 - Take [2, [3, 4]] and then take [2] and [3, 4].

  • Step 3 - Take [3, 4] separately and then keep it.

  • Step 4 - Take [5] and keep it.

Output -

[1, 2, 3, 4, 5]

Different approaches to flatten arrays

1. flat()

const arr = [1, [2, [3, 4]], 5];

console.log(arr.flat());        // [1, 2, [3, 4], 5]
console.log(arr.flat(2));       // [1, 2, 3, 4, 5]
console.log(arr.flat(Infinity)); // [1, 2, 3, 4, 5]

2. Recursion

function flattenArray(arr) {
  let result = [];

  for (let element of arr) {
    if (Array.isArray(element)) {
      result = result.concat(flattenArray(element));
    } else {
      result.push(element);
    }
  }

  return result;
}

const arr = [1, [2, [3, 4]], 5];
console.log(flattenArray(arr)); // [1, 2, 3, 4, 5]

3. reduce()

function flatten(arr) {
  return arr.reduce((acc, val) => 
    acc.concat(Array.isArray(val) ? flatten(val) : val), []
  );
}

const arr = [1, [2, [3, 4]], 5];
console.log(flattenArray(arr)); // [1, 2, 3, 4, 5]

4. Iterative Stack

function flattenArrayIterative(arr) {
  const stack = [...arr];
  const result = [];

  while (stack.length) {
    const next = stack.pop();

    if (Array.isArray(next)) {
      stack.push(...next);
    } else {
      result.push(next);
    }
  }

  return result.reverse();
}

const arr = [1, [2, [3, 4]], 5];
console.log(flattenArrayIterative(arr)); // [1, 2, 3, 4, 5]

Common Interview scenarios

  1. Fully flatten an array

  2. Flatten an array at a specific depth

  3. Set flatten array and remove duplicate

  4. Flatten and add sum of elements


Table diagram

Approach

Readability

Performance

Interview Value

Best Use Case

flat()

⭐⭐⭐⭐⭐

⭐⭐⭐⭐

⭐⭐

Everyday use

Recursion

⭐⭐⭐⭐

⭐⭐⭐⭐

⭐⭐⭐⭐⭐

Interviews

reduce()

⭐⭐⭐⭐

⭐⭐⭐⭐

⭐⭐⭐⭐

Functional style

Iterative Stack

⭐⭐⭐

⭐⭐⭐⭐⭐

⭐⭐⭐⭐⭐

Deep nesting