-1

I want to reduce the dimensions of my array from array of arrays to a single array. The structure may be heavily nested.

I tried using reduce and map functions and running a loop, but it is very complicated. Wanted to know if there is a simpler solution

Input example:  a = [[1],[2,3,['abc']],[5,[6,['def']]]]
Output expected: a = [1, 2, 3, "abc", 5, 6, "def"]
Giridhar
  • 46
  • 6

2 Answers2

1

I think this would be a great example to use the new flat function in arrays refer [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat]

let a = [[1],[2,3,['abc']],[5,[6,['def']]]]
a = a.flat(Infinity);  // since the nesting may be highly deep

You can use a recommended polyfill since the browser support is not very high.

Alternatives are to use reduce and concat, which is explained in the link above.

//to enable deep level flatten use recursion with reduce and concat

var arr1 = [1,2,3,[1,2,3,4, [2,3,4]]];
function flattenDeep(arr1) {
   return arr1.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val), []);
}
flattenDeep(arr1);// [1, 2, 3, 1, 2, 3, 4, 2, 3, 4]
Dhananjai Pai
  • 5,914
  • 1
  • 10
  • 25
0

You can use flat with the level of nesting to make it a single array

var a= [[1],[2,3,['abc']],[5,[6,['def']]]];
console.log(a.flat(3))
ellipsis
  • 12,049
  • 2
  • 17
  • 33