0

I have an array of arrays of objects. so it looks something like [[{}{}],[{}{}{}],[{}{}], [{}{}{}{}]]...etc I need to loop through each object in this array. Problem is that would require a nested for loop, which isn't bad but I was wondering if there is any way I could use the spread operator when I'm putting it in the original array. outerArray.push(...innerArray), something along the lines of that. That didn't work but is there something similar?

thatdevop
  • 819
  • 2
  • 8
  • 19

2 Answers2

2

You can use Array.prototype.flat to convert a nested array, into a flattened array

var arr1 = [1, 2, [3, 4]];
arr1.flat(); 
// [1, 2, 3, 4]

var arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]

var arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2);
// [1, 2, 3, 4, 5, 6]

For older browsers, you can refer to other answers

Sam Denty
  • 3,693
  • 3
  • 30
  • 43
0

Just adding another option here that doesn't require passing the depth in:

const deepFlatten = arr =>
  [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v)))

call with deepFlatten(outerArray)

timmcliu
  • 1,769
  • 1
  • 13
  • 12