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?

asked Dec 18, 2018 at 16:58
2
  • Use [].concat(...outerArray) Commented Dec 18, 2018 at 16:59
  • @MohammadUsman that's a shallow flat Commented Dec 18, 2018 at 17:02

2 Answers 2

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

answered Dec 18, 2018 at 17:00
Sign up to request clarification or add additional context in comments.

2 Comments

That's probably how I would've done it, clean, simple & straight to the point.
great answer! i might stick with nested loops but this works.
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)

answered Dec 18, 2018 at 17:09

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.