Flattening Multidimensional Arrays in JavaScript

Introduction

Arrays are an often-used part of any developer's toolkit. They're used to store multiple values in a single variable, which can be extremely useful. But what happens when you have an array... of arrays? This is known as a multidimensional array, and it's not always the easiest thing to work with. That's where flattening comes in.

In this Byte, we'll explore what multidimensional arrays are, why you might want to flatten them, and how you can do so using the flat() method.

Multidimensional Arrays

A multidimensional array is essentially an array that contains other arrays. These inner arrays can themselves contain arrays, leading to multiple levels of depth. Here's a simple example:

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

This will output:

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

As you can see, each inner array is its own distinct entity within the outer array.

Why flatten arrays?

So why would you ever want to flatten an array. After all, isn't the whole point of a multidimensional array to have multiple levels of depth? While this is true, there are still times when it can be beneficial to flatten your arrays.

Let's say you want to find the sum of all the numbers in our multiArray from the previous section. If you tried to use the reduce() method directly on multiArray, you'd run into problems because reduce() expects a one-dimensional array. By flattening the array first, you can easily find the sum of all the numbers.

Using the flat() Method

The flat() method is a built-in JavaScript method that can be used to flatten multidimensional arrays. By default, it will only flatten one level deep. Here's how you can use it:

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

This will output:

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

As you can see, flat() has taken our multidimensional array and turned it into a one-dimensional array. Now we can more easily find the sum of all the numbers using reduce():

let sum = flatArray.reduce((a, b) => a + b, 0);
console.log(sum);
Get free courses, guided projects, and more

No spam ever. Unsubscribe anytime. Read our Privacy Policy.

This will output:

45

There you have it! We've successfully flattened our multidimensional array using the flat() method, making it much easier to work with.

Using the reduce() Method

JavaScript's reduce() method is a powerful tool for condensing arrays. It applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single output value.

Let's see how we can use the reduce() method to flatten an array of arrays:

let arrays = [[1, 2, 3], [4, 5], [6]];
let flattened = arrays.reduce((acc, curr) => acc.concat(curr), []);
console.log(flattened); // Output: [1, 2, 3, 4, 5, 6]

In the reduce() method, acc (the accumulator) starts off as an empty array []. For each sub-array curr in arrays, we concatenate curr to acc and return the result. This continues until we've processed all the sub-arrays, resulting in a single, flattened array.

Using the concat() Method

The concat() method is used to merge two or more arrays. It does not change the existing arrays, but instead returns a new array.

Here is how you can use concat() to flatten an array of arrays:

let arrays = [[1, 2, 3], [4, 5], [6]];
let flattened = [].concat.apply([], arrays);
console.log(flattened); // Output: [1, 2, 3, 4, 5, 6]

Here we're using apply() to call concat() with the arrays as arguments. This effectively concatenates all the sub-arrays into one array. Keep in mind that this only works for 2-dimensional arrays, but not any larger.

Flattening Nested Arrays

Flattening nested arrays, or arrays within arrays, can be a bit trickier. However, the nice thing about the flat() method is that we can specify the depth of arrays to flatten.

let arrays = [[1, 2, [3]], [4, [5, [6]]]];
let flattened = arrays.flat(2);
console.log(flattened); // Output: [1, 2, 3, 4, 5, 6]

In this case, we're telling flat() to flatten up to 2 levels of nested arrays. If you have an array with unknown depth, you can pass Infinity to flat() to flatten all nested arrays, no matter how deep.

Note: The flat() method is not supported in Internet Explorer. Consider using a polyfill or Babel plugin to provide this functionality for older browsers.

Conclusion

In this Byte, we've explored a few methods to flatten arrays in JavaScript, including reduce(), concat(), and flat(). Each method has its use cases and limitations, and understanding these can help you choose the right tool for your specific needs. Remember, while flat() is a convenient method, it may not always be the best choice due to its lack of support in older browsers.

Last Updated: August 31st, 2023
Was this helpful?

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms