Array.from

Array.from

Β·

2 min read

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