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?
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
2 Comments
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)
[].concat(...outerArray)