DEV Community

Discussion on: 28 Javascript Array Methods: A Cheat Sheet for Developer

Collapse
 
konrud profile image
Konstantin Rouda

Array flat example has a wrong result.

Applying Array.flat() without any value will only flat a provided array up to one level. In the provided example you have an array with 2 nesting levels. Thus, the result should be [1, 2, 3, 4, [5, 6]].

If you know the number of nesting arrays you can provide it (e.g. list.flat(2)), otherwise you can use global property Infinity with it (e.g. list.flat(Infinity)) which will flat all number of nesting arrays.

Thus your example might be rewritten in the following way


// Code
const list = [1, 2, [3, 4, [5, 6]]];
list.flat(Infinity); // [1, 2, 3, 4, 5, 6]

// OR
list.flat(2); // [1, 2, 3, 4, 5, 6]

Enter fullscreen mode Exit fullscreen mode
Collapse
 
devsmitra profile image
Rahul Sharma

My bad, Thank you so much for pointing it out.