1

I know there are a lot of ways to flatten an array in javascript, but I want to know what's the best way to flatten an n-level array into a 2D array

Input array looks like this : [[[[1,2]]],[2,3]] i need to convert this into [[1,2],[2,3]]

I tried using array.flat() but it flattens only 1 step and I also tried array.flat(Infinity) but it flattens the whole array into 1D array

the problem is am not sure how deeply nested my input array is. I could think of iterating recursively but am looking if js has any optimised&ready-made way of achieving this?

2
  • Have you tried lodash methods? Commented May 7, 2021 at 10:58
  • can you suggest which one to use ? Commented May 7, 2021 at 11:12

2 Answers 2

2

You could combine map and flat(Infinity) methods to flatten each sub-array to 1D.

const flatDeep = data => data.map(e => e.flat(Infinity))
console.log(flatDeep([[[[1,2]]],[2,3]]))
console.log(flatDeep([[[[1,2]]],[2,[[[3, [4]]]]]]))

Sign up to request clarification or add additional context in comments.

5 Comments

This looks good but it doesn't keep the last level of grouping intact.. i want [[[[1,2],[3,4]]],[2,3]] to be converted to [[1,2],[2,3],[2,3]] not [[1,2,3,4],[2,3]]
@aravind_reddy So what should be the result in this case [[[[1,2]]],[2,[[[3, [4]]]]]]?
it should be [[1,2],[2,3,4]] i guess
@aravind_reddy So what is the logic there?
sorry i think what you gave is good I will post the other requirements in another question altogether
0

Iterate the array and then use Array.flat(Infinity) method.

const list = [[[[1,2]]],[2,3],[[3,4]]]
const result = [];
for (value of list) {
  result.push(value.flat(Infinity));
}
console.log(result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.