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?
Asked
Active
Viewed 35 times
0

thatdevop
- 819
- 2
- 8
- 19
-
Use `[].concat(...outerArray)` – Mohammad Usman Dec 18 '18 at 16:59
-
@MohammadUsman that's a shallow flat – quirimmo Dec 18 '18 at 17:02
2 Answers
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
-
1That's probably how I would've done it, clean, simple & straight to the point. – JO3-W3B-D3V Dec 18 '18 at 17:04
-
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