aravind_reddy
aravind_reddy

Reputation: 5476

best way to flatten n-level array into 2d array

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?

Upvotes: 1

Views: 314

Answers (2)

Rahul Kumar
Rahul Kumar

Reputation: 3157

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);

Upvotes: 0

Nenad Vracar
Nenad Vracar

Reputation: 122067

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]]]]]]))

Upvotes: 2

Related Questions