Effective Ways to Flatten Nested Arrays in JavaScript Explained

Flattening means converting a nested array (an array inside arrays) into a single level array. If I have multiple levels like [1, 2, [3, 4], [[5, 6]]], dealing with it is difficult. I don’t want arrays inside arrays at different levels. I want everything at one single level like [1, 2, 3, 4, 5, 6]. If you want to do more with array transformations after flattening, see map-filter-reduce.

What is JavaScript Array Flattening

  Effective Ways to Flatten Nested Arrays in JavaScript Explained  1   JavaScript Array Flattening is taking a nested array and reducing it to a single level. A multi-level array has arrays inside arrays, and the goal is to resolve those inner arrays into a flat sequence of values. Here is the kind of nested data I am talking about:
const nested = [1, 2, [3, 4], [[5, 6]]];
I want the result as a single array.

Flat method

The first method is the built-in Array.prototype.flat. Step 1: Keep your original nested array.   Effective Ways to Flatten Nested Arrays in JavaScript Explained  2  
const nested = [1, 2, [3, 4], [[5, 6]]];
  Effective Ways to Flatten Nested Arrays in JavaScript Explained  3   Step 2: Create a new variable and call flat on the original array.   Effective Ways to Flatten Nested Arrays in JavaScript Explained  4  
const flattenedOnce = nested.flat();
console.log(flattenedOnce);
// [1, 2, 3, 4, [5, 6]]
  Effective Ways to Flatten Nested Arrays in JavaScript Explained  5   By default, flat resolves only one level. You can see [5, 6] is still inside an inner array after a single flatten. If you only need to remove one nesting level, this is enough. If you plan to analyze values after flattening, you might want to count frequencies.

Unknown depth

If you do not know how deep the nested arrays go, pass Infinity to flat. This resolves every level until you get a single level array. Step 1: Call flat with Infinity.   Effective Ways to Flatten Nested Arrays in JavaScript Explained  6  
const flattenedAll = nested.flat(Infinity);
console.log(flattenedAll);
// [1, 2, 3, 4, 5, 6]
  Effective Ways to Flatten Nested Arrays in JavaScript Explained  7   Step 2: Work with the fully flattened result.   Effective Ways to Flatten Nested Arrays in JavaScript Explained  8  
// example: sum the values
const sum = flattenedAll.reduce((a, b) => a + b, 0);
console.log(sum); // 21
  Effective Ways to Flatten Nested Arrays in JavaScript Explained  9   If you are moving from data work to UI, take a look at a simple dropdown menu pattern.

Final thoughts

Flattening arrays in JavaScript is straightforward with flat. By default, flat reduces one level. If you are unsure about the depth, use flat(Infinity) to resolve all levels and get everything at the same level.

Leave a Comment