Today’s function is array.from(), mdn description here.
This function creates an array from whatever it has been given.
For example, if you give it a string it will split the string into chars and build an array from that. You could also give it an existing array and a function, and it will create a new array from the results of applying the function to each item in the original array.
For this second use case, it's interesting to consider when to use array.from() vs array.map(). Would welcome any comments :)
I've done my own version of the docs with sketches together. Here’s the folder for array.from. Check out the readme to see how you can run the examples.
Top comments (4)
For those reading this post I'll show you another interesting use for
array.from
.Try this:
Then try this:
Array.from
can be used to create a deep copy of an array. If we simple assign a value of an existing array to a new array it creates a shallow copy of the existing array.Thanks for this :). The two snippets you’ve given seem exactly the same to me - am I missing something?
Yes, you are right Charlotte, I corrected my mistake.
I just edited the second snippet, in the second line I was supposed to use
Array.from
.I hope it makes sense now.
I see! Very cool, thanks for sharing hadn't thought of that use case.