The JavaScript function Array.from
is not often discussed, but it is great!
Sometimes we run into something which is array-like, but is not actually an array. It would be nice to use the standard array methods like forEach
or filter
, but they're not directly available since the thing is not really an array.
π§
Array.from
to the rescue!
It turns things into an array, which means we can use the array methods we're already familiar with.
Here are some examples array-like things which I've found useful to convert to an array using Array.from
:
Here is an example of removing a frisbee π₯ from a string of sports balls using the filter
array method.
const realSportsBalls = Array.from('β½ππβΎπ₯πΎπππ₯π±')
.filter(ball => ball !== 'π₯')
.join('');
π€ΉββοΈ
What exactly is an "array-like" thing? It is an object with a length
property and indexed elements. "Indexed elements" means that some of the keys of the object are numbers.
Array.from({
length: 3,
0: 'A',
1: 'B',
2: 'C',
});
// Evaluates to [ "A", "B", "C" ]
π«
Read more about Array.from
:
developer.mozilla.org/en-US/docs/Web/JavaSc..
w3schools.com/jsref/jsref_from.asp
π‘π‘π‘
Cover photo by braincontour from Pexels