Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Flatten Multidimensional array with Javascript #4

Open
blackkspydo opened this issue Oct 10, 2022 · 0 comments
Open

Flatten Multidimensional array with Javascript #4

blackkspydo opened this issue Oct 10, 2022 · 0 comments
Assignees

Comments

@blackkspydo
Copy link
Owner

blackkspydo commented Oct 10, 2022


description: Flatten your deeply nested multi-dimentional array with this simple Javascript trick.
category: snippets
slug: flatten-multi-dimentional-array
canonical: https://blackkspydo.com/blog/flatten-multi-dimentional-array
image: https://user-images.githubusercontent.com/58302072/194879157-5cbb3229-2e6a-416a-a342-22166ef93875.png

Problem

You have a multidimensional array and you want to flatten it into a single array.

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

Solution

Here, we use the Array.prototype.reduce() method to flatten the array. We use the Array.isArray() method to check if the current element is an array. If it is, we recursively call the flatten() function on it and concatenate the result to the accumulator. If it is not, we simply concatenate the element to the accumulator.

const flatten = arr => arr.reduce((acc, val) => Array.isArray(val) ? acc.concat(flatten(val)) : acc.concat(val), []);

Usage

flatten(arr); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

References

@blackkspydo blackkspydo changed the title Flatten Multidimensional array with javascript Flatten Multidimensional array with Javascript Oct 10, 2022
@blackkspydo blackkspydo self-assigned this Oct 12, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant