You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
You have a multidimensional array and you want to flatten it into a single array.
constarr=[[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.
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.
Solution
Here, we use the
Array.prototype.reduce()
method to flatten the array. We use theArray.isArray()
method to check if the current element is an array. If it is, we recursively call theflatten()
function on it and concatenate the result to the accumulator. If it is not, we simply concatenate the element to the accumulator.Usage
References
The text was updated successfully, but these errors were encountered: