Array.from can do much more

ยท

2 min read

My encounters with Array.from made me have a limiting intention about it. At most, it was used only to convert strings to arrays.

In fact, in one of the very popular library docs, it was mentioned that it is only two array methods that can be used to render a list ( array.map and array.filter), OMG ๐Ÿ˜ฒ, little do we all know array.from does it too. It does it even cleaner and more precise.

During the quick read of this article, you would have seen use cases, and why you should use Array.from more.

Reduce redundancy of splitting a string and mapping

Array.from can bring in some elegancy when trying to split a string and mapping each value.
For example, given we have a string and to repeat each letter in it twice, the default way to have solved this would have been

const city = "lagos"
city.split('').map(e=> e.repeat(2)).join('') //llaaggooss

Array.from does it better with 2 letter spaces lesser

const city = "lagos"
Array.from(city, e=> e.repeat(2)).join('') //llaaggooss

Map throw any iterable

Array.from is not limited to strings, and that's where it shines. It can be used on any iterable whatsoever.

//sets
const ss = new Set([1,2,3,4])
Array.from(ss) // [1,2,3,4]

//array
Array.from(["india", "china", "russia"]) // [ "india", "china", "russia" ]

//string
Array.from("russia") // [ "r", "u", "s", "s", "i", "a" ]

Its second value behaves like a map function, it can be used to manipulate each returned value from executing the iterables as we showed before.

//sets
const ss = new Set([1,2,3,4])
Array.from(ss, e=> e*4) // [ 4, 8, 12, 16 ]
ย