Purpose of Array.from()

Array.from({ length: 4 }
Array.from({ length: 4 }
Hello guys, from mdn docs, mdn, I understood what Array.from does but when it takes an object as argument what does it do? Can someone explain pls.
43 Replies
Jochem
Jochem3d ago
It takes an iterable and turns it into an array
Faker
FakerOP3d ago
yep but in our case, we are passing an object as argument, even an object is an iterable with key, value pair but with only 1 property, do we expect an array of size 1 ?
Jochem
Jochem3d ago
querySelectorAll for example returns something that isn't technically an array Mdn says
array-like objects (objects with a length property and indexed elements).
Though I've honestly never used that So I think if you ran that code, you'd get an array with four empty indexes
Faker
FakerOP3d ago
yeahh just tried it out, I got an array of size 4 the length property behaves as the size of the array to be returned in this case
Jochem
Jochem3d ago
And if you ran it on an object that didn't have length, it'd probably throw an error
Faker
FakerOP3d ago
yepp ty !
StefanH
StefanH3d ago
It's used to convert other kinds of collections into arrays too. like Sets
const set = new Set();
// ...
Array.from(set).sort(/* */)
const set = new Set();
// ...
Array.from(set).sort(/* */)
and set is great if you need a collection that automatically gets rid of duplicates and where the order doesn't matter
Faker
FakerOP3d ago
yepp I see, thanks 1
13eck
13eck3d ago
It allows you to turn an iterable or array-like into an actual array. This is important because array-likes don’t have all of the array methods. So if you get, for example, a node list (from document.query selectorAll() you can’t filter, map, or forEach. Also, using the optional second argument—a mapping function—you can create a custom array. I’m on mobile and at work so I can’t give an example right now, sorry.
Faker
FakerOP3d ago
np, the explanation was perfect, will figure out the rest
ἔρως
ἔρως3d ago
you can also use it with a string, to get all the characters in an array
ἔρως
ἔρως3d ago
No description
Faker
FakerOP3d ago
yepp
ἔρως
ἔρως3d ago
something interesting: it converts a sparse array into an array with undefined values
ἔρως
ἔρως3d ago
No description
Faker
FakerOP3d ago
oh can be useful, ty !
ἔρως
ἔρως3d ago
oh, yeah, in case you might be surprised about stuff like this
No description
StefanH
StefanH3d ago
wtf this function does way too many things at once i'm not a fan
13eck
13eck3d ago
It only does one thing: convert a non-array to an array. It’s very good at it, and has to be considering everything that’s not an array that it needs to handle
StefanH
StefanH3d ago
it sure is good at spitting out arrays but the amount of different behaviors all funneled through a single function isn't very nice i get why they have to do it though
Jochem
Jochem3d ago
but the examples epic gave aren't different behaviors at all though they're quirks of the language
Jochem
Jochem3d ago
a string, for example, has a length property, and you can access characters by index:
No description
ἔρως
ἔρως3d ago
yup as long as it looks like an array, it will be converted to an array it's the equivalent of this:
let array = [];

for(let i = 0; i < value.length; i++) {
array[i] = value[i] ?? undefined;
}
let array = [];

for(let i = 0; i < value.length; i++) {
array[i] = value[i] ?? undefined;
}
(it's not the same, as it handles iterators too)
Jochem
Jochem3d ago
I think it's easier to understand if you explain it that if it's either an iterable, or an object with a length property and indexable values, it'll convert to an array a string works because everything in JS is an object, it has a length property, and you can access letters by index
ἔρως
ἔρως3d ago
yeah, you're right i just wanted to show that it doesn't do as much as stefanh was saying thast it isn't a super magical method that does a million trillion things
Ganesh
Ganesh3d ago
Just an note. Some nodelist are live collections. (Element.children for example) So array from can also be used to convert them into static arrays. Useful for when you're doing something while iterating on the collection that causes the node to be removed
13eck
13eck3d ago
Ok, now that I'm home I can write out an example. Say you want an array of 10 random numbers between 1 and 6:
Array.from({length: 10}, () => Math.floor(Math.random() * 6) + 1);
Array.from({length: 10}, () => Math.floor(Math.random() * 6) + 1);
The second parameter is a mapping function. Whatever it returns is made the value for that specific index. And as epic pointed out, if you use the map function on an array it skips any empty/undefined values.
ἔρως
ἔρως3d ago
just skips empty values empty is not the same as undefined
13eck
13eck3d ago
That's what I meant :p
ἔρως
ἔρως3d ago
yup, but it is important to be a pedantic butt, because both are very different
13eck
13eck3d ago
::nods sagely::
ἔρως
ἔρως3d ago
but i didn't knew it has a mapping function
13eck
13eck3d ago
No? That's the primary way I use it
ἔρως
ἔρως3d ago
i just use it to get an array from something that isn't an array
13eck
13eck3d ago
I mostly use it to make arrays
ἔρως
ἔρως3d ago
i think the last time i used it, it was to convert a set to an array
Faker
FakerOP2d ago
yep I see, thanks !
Rägnar O'ock
Rägnar O'ock2d ago
I use that a lot to initialize arrays when doing stuff on index based data Though now I try to use iterators when I can instead IIRC it's more perfomant to do Array.from then .map than it is to use the mapping function. But the last time I benchmarked that was at least 2 years ago and ot might have changed since then (and even at the time the diff wasn't huge)
13eck
13eck21h ago
Just ran it on both jsperf.app and jsbench.me and Array.from({length: 10_000_000}, () => Math.floor(Math.random() * 6) + 1); outperformed Array.from({length: 10_000_000}).map( () => Math.floor(Math.random() * 6) + 1); by a small amount (~11% slower on jsperf.app and ~14% slower on jsbench.me).
Rägnar O'ock
Rägnar O'ock16h ago
JS Benchmark
A straightforward online JavaScript benchmarking tool and REPL with support for ES modules and libraries.
Rägnar O'ock
Rägnar O'ock16h ago
iterators are not great perfwise are they...
No description
13eck
13eck16h ago
Oof
Rägnar O'ock
Rägnar O'ock15h ago
with a push in a for loop, for reference :
No description

Did you find this page helpful?