Skip to content
the poor coder

Flatten a multidimension array

Poor Man
Published
Reading time
1 min read

Flattening a multidimensional array is a process of taking an array with multiple sub-arrays and returning a single array with all the values of the original arrays combined. This can be done by looping through each sub-array and pushing each element into a single array.

JavaScript

//Flatten a multi-dimensional array
function flattenArray(arr) { 
    let flatArray = [];
    for (let i = 0; i < arr.length; i++) {
        if (Array.isArray(arr[i])) {
            flatArray = [...flatArray, ...flattenArray(arr[i])];
        } else {
            flatArray.push(arr[i]);
        }
    }
    return flatArray;
}

For example, given the array [1, [2, [3, 4], 5], 6], the flattened array would be [1, 2, 3, 4, 5, 6]. The code example above is written in JavaScript and uses a recursive approach to loop through all the sub-arrays and push each element into a single array.

Another way to flatten a multidimensional array is to use the reduce method. This works similarly to a for loop but it is a bit more concise and can be written in one line of code. Here is an example below.

JavaScript

//Flatten a multi-dimensional array using reduce
let flattenedArray = arr.reduce((acc, cur) => 
    Array.isArray(cur) ? [...acc, ...flattenArray(cur)] : [...acc, cur], []);

The reduce method starts with an empty array and then loops through each element of the original array. If the element is an array, it will be flattened and added to the accumulator array. If it is not an array, it will be pushed into the accumulator array.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC