CoverT 10: Array.from()

codeInteractive Code Example

The Array.from() method creates a new shallow-copied Array instance from an array-like or iterable object.

This can be really useful when you want to convert a Map or Set to an Array, or as an alternative way to turn a string into an Array (e.g. instead of using something like "MyString".split(""))

// array-like object
console.log(Array.from('hello')); // ["h","e","l","l","o"]

// using an optional mapper function
console.log(Array.from([1,2,3], x => x * 10)); // [10,20,30]

// iterable objects (Map & Set)
console.log(Array.from(new Set([1,2,3]))); // [1,2,3]
console.log(Array.from(new Map([[1,1.1],[2,2.2],[3,3.3]]))); // [[1,1.1],[2,2.2],[3,3.3]]