r/javascript • • Mar 02 '19

Useful javascript one-liners.

https://medium.com/@smellycode/js-one-liners-8bc0a6af2345?source=friends_link&sk=a9295a05aef9e514e137fca7eeb89cd1
344 Upvotes

96 comments sorted by

View all comments

Show parent comments

-2

u/[deleted] Mar 02 '19

That works, but only for explicitly named arrays. What about the generalized case?

3

u/hypercurrency Mar 02 '19

I don't know what the generalised case you're referring to? 😐 I'm sure that I am missing something. I am no expert but anytime I've needed to merge arrays, that's what I do.

0

u/[deleted] Mar 02 '19

Oh, I see. What if you want to merge a bunch of arrays? By the generalized case, I meant something that would work for any number of arrays including no arrays at all.

Using OP's merge function `const merge = (...arrays) => [].concat(...arrays)`, you can merge `[], [1], [1,2], [1,2,3], [1,2,3,4]` without having to give a name to each array. What if you have 100 arrays?

4

u/LookingForAPunTime Mar 02 '19 edited Mar 02 '19

[...[], ...[1], ...[1, 2], ...[1, 2, 3], ...[1, 2, 3, 4]]

But more to the point, you’re not going to have an ā€œunnamedā€ array. Literally anything you don’t write by hand is going to have a reference of some kind, and you can spread it, even if you need to wrap the spread in round brackets.

And if you have an array of arrays, there’s Array.prototype.flat().