DEV Community

Discussion on: 2 Uses of concat method when working with arrays in JavaScript

Collapse
lukeshiru profile image
LUKESHIRU

Worth mentioning than for flattening, you can just use Array.prototype.flat (mdn):

[[1, 2, 3], [4, 5, 6]].flat(); // [1, 2, 3, 4, 5, 6]
Enter fullscreen mode Exit fullscreen mode

Another "flat related" method is Array.prototype.flatMap (mdn), which you can use like this:

[1, 2, 3].flatMap(value => [value, value *2]); // [1, 2, 2, 4, 3, 6]
Enter fullscreen mode Exit fullscreen mode

Generally is better to use any of these to flatten instead of concat.

Cheers!

Collapse
kritikapattalam profile image
Kritika Pattalam Bharathkumar Author

100% agree with you. Using Array.prototyoe.flat is the most efficient way, but the post was more about what concat is possible of doing.
Thanks for adding this, its helpful for others reading that concat is not the only way to flatten arrays.