DEV Community

Cover image for 7 Practical Use Cases of JavaScript Array.from
Tasnim Reza
Tasnim Reza

Posted on

7 Practical Use Cases of JavaScript Array.from


Array.from ( items [ , mapfn [ , thisArg ] ] )


items: required, it could be Iterable like Map, Set, WeakMap, WeakSet or arrayLike object like regular Array, string, NodeList, HTMLCollection and so on.

mapfn: optional, It is a regular map function like

function(item, index){
  return item*2;

thisArg: optional It could be any type of object which can be accessible from inside the mapfn via this keyword

Array.from([1,2,3], function(item, index){
console.log(this); //1
}, 1);

1. Transform iterable to array.

We can transform any iterable to array. Let's see some examples for built-in iterables.

Array.from(new Set([1,2]));

Array.from(new Map().set(1, 1));

2. Find unique items from array

We can use this method to identify unique items from array, though i prefer to use spread operator. like [... new Set([1,1,2])]

Array.from(new Set([1,1,2]));

3. Create array from user-defined iterable

Sometimes we need to define our own iterable objects. We can convert them into array in a similar fashion.

function* simpleIterator() {
    yield 1;
    yield 2;

4. Clone any array 5 Some use cases for arrayLike object

Since Array.from shallow copies item so we can use to clone any array.

let foo = [1,2,3];
let bar = Array.from(foo);
foo === bar

The object equality foo === bar false means, they aren't same object though they have the same items.

5. Convert string to character array

Since string is an arrayLike object so convert them into array.

Array.from('how are you');
["h", "o", "w", " ", "a", "r", "e", " ", "y", "o", "u"]

//It is Unicode supported
["I", "💖", "U"]

6. Convert arrayLike object to array

Another useful use-case would be mapping items while converting them into an array. For example HTMLCollection is an arrayLike object, what if we want to change the textContent?

let divs = document.getElementsByTagName('div');
Array.from(divs, div=> div.textContent = 'hello')
["hello", "hello", ...]

7. Prefill an array

Also, it can be useful to prefill an array

Array.from({length:3}, x=> 0);
[0, 0, 0]

Further more


Top comments (0)