How to Easily Flatten Multidimensional Arrays in JavaScript

How to Easily Flatten Multidimensional Arrays in JavaScript

Ferenc Almasi β€’ 2020 August 11 β€’ Read time 2 min read
  • twitter
  • facebook
JavaScript

The spread operator comes to save us all once again. One of the cleanest ways to flatten a multidimensional array in JavaScript can be achieved with concat and the spread operator in the following way:

Copied to clipboard! Playground
// Flatten multidimensional array with the combination
// of concat and the spread operator

const multidimension = [πŸ₯—, [🍌, 🍎, πŸ‡], 🍣, [🐟, 🍚]];

[].concat(...multidimension); // This will return: [πŸ₯—, 🍌, 🍎, πŸ‡, 🍣, 🐟, 🍚]

const multidimension = [1, [2, 3, 4], 5, [6, 7]];

[].concat(...multidimension); // This will return: [1, 2, 3, 4, 5, 6, 7]
flatten.js

However, this solution will only work if the depth level of the array is not greater than 1. To battle this, you could use Array.prototype.flat:

Copied to clipboard! Playground
// The depth of the array is 2
const multidimension = [1, [2, 3, 4], 5, [6, 7, [8, 9, 10]]];

[].concat(...multidimension); // Using the previous solution, this will return: [1, 2, 3, 4, 5, 6, 7, Array(3)]

multidimension.flat(2); // This will return: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
multidimension.flat(Infinity); // If you don't know the depth of the array, simply pass Infinity
flatten.js

The function takes in one parameter: the depth of the array. It defaults to 1. Keep in mind that this built-in function is not supported in IE. If you also need support for IE, you can either use a polyfill or the below function which achieves the same recursively:

Copied to clipboard! Playground
const flatten = (array, output) => {
    array.forEach(item => {
        if(Array.isArray(item)) {
            flatten(item, output);
        } else {
            output.push(item);
        }
    });

    return output;
};

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

flatten(multidimension, output); // This will return [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
flatten.js
How to Easily Flatten Multidimensional Arrays in JavaScript
If you would like to see more Webtips, follow @flowforfrank

Resource

  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.