JS: Array.from

By Xah Lee. Date: . Last updated: .

(new in ECMAScript 2015)

Array.from(xlist)

Convert xlist to array.

arg can be Array-Like Object or Iterable Object object.

If arg is Sparse Array, empty slots are treated as having value of undefined

// If arg is Sparse Array, empty slots are treated as having value of undefined
console.log(Array.from([3, , , 5]));
// [ 3, undefined, undefined, 5 ]

console.log(Array.isArray(Array.from([3, , , 5])));
// true
// Convert Array-Like Object to Array
console.log(Array.from({ 0: "a", 1: "b", length: 2 }));
// [ "a", "b" ]

// empty slots are given values of undefined
console.log(Array.from({ length: 3 }));
// [ undefined, undefined, undefined ]
// Convert string to array of chars
console.log(Array.from("🦋⭐🌞"));
// [ "🦋", "⭐", "🌞" ]
Array.from(xlist, f)

Apply f to each.

The function f is passed 2 args:

  1. current element
  2. current index
// Convert string to array of chars
console.log(Array.from("🦋⭐🌞", (a, b) => [a, b]));
// [ [ "🦋", 0 ], [ "⭐", 1 ], [ "🌞", 2 ] ]
Array.from(xlist, f, thisBinding)

JavaScript. Object Properties to Array

JavaScript. Iterable, Iterator