Array.from in JavaScript
Array.from simplifies array conversion by providing one simple interface to turn objects that can be iterated through to arrays. Normally, separate operations are required for different types:
const str = 'test'; const strArray = str.split(''); const printArguments = function() { console.log([].slice.call(arguments)); } console.log(strArray); // [ 't', 'e', 's', 't' ] printArguments('test1', 'test2', 'test3'); // [ 'test1', 'test2', 'test3' ]
This is simplified with Array.from:
const strArray2 = Array.from(str); const printArguments2 = function() { console.log(Array.from(arguments)); } console.log(strArray); // [ 't', 'e', 's', 't' ] printArguments('test1', 'test2', 'test3'); // [ 'test1', 'test2', 'test3' ]
It is also useful for new ES6 Objects like Set and Map:
const map1 = new Map([['property1', 'value1'], ['property2', 'value2']]); const set1 = new Set(['test1', 'test2', 'test1', 'test3']); const map1Str = Array.from(map1); const set1Str = Array.from(set1); console.log(map1Str); // [ [ 'property1', 'value1' ], [ 'property2', 'value2' ] ] console.log(set1Str); // [ 'test1', 'test2', 'test3' ]
Browser support is good other than there is no IE support, only MS Edge. MDN has a polyfill that can help in that case.
Github Location: https://github.com/Jacob-Friesen/obscurejs/blob/master/2017/arrayFrom.js








