Categories:

Converting array-like objects into arrays using Array.from() method (ECMAScript 6)

Starting in ECMAScript 6 (finalized in August 2014) supports a more generic Array method for converting an array-like object into one of its own. Behold Array.from(), which is currently supported in Firefox 22+ (as of writing), and has the following syntax:

Array.from(arraylike, [mapFn[, thisArg]])

This method supports the following 3 parameters:

  • arrayLike: Any array-like or iterable object that you wish to convert to a true array.

  • mapFn (optional): An optional function that gets called on each element within the target object.

  • thisArg (optional): An optional parameter that lets you specify a different object as the "this" object inside mapFn function.

In the following, we convert the arguments object of a function into a true array using Array.from() or Array.prototype.slice depending on browser support:

function test(){
	var argarray = (Array.from)? Array.from(arguments) : Array.prototype.slice(arguments)
	return argarray
}

test("George", "Kelly", "Julia") // returns array ["George", "Kelly", Julia"]

Array.from() can also be used on a string to convert each character into an array element:

Array.from("George") // returns ["G", "e", "o", "r", "g", "e"]

This yields the same result as using String object's split() method to change a string into an array:

"George".split("") // returns ["G", "e", "o", "r", "g", "e"]

While Array.from() typically is used to convert array imposters into true arrays, you can also use it on an actual array to step through and manipulate the individual elements inside the array, by making use of the optional mapFn function. In the below, we manipulate an array of numbers so their values are tripled using Array.from:

var newArray = Array.from([1,2,3,4], function(el){
	return el * 3
})

console.log(newArray) // [3,6,9,12]