JS: Array.from
(new in ECMAScript 2015)
Array.from(x_iterable)-
Convert x_iterable to array.
argument can be Array-Like Object or Iterable Object object.
If argument is Sparse Array, empty items are treated as having value of undefined.
/* Convert Sparse Array to dense array. Empty items are treated as having value of undefined. */ console.log(Array.from([3, , , 5])); // [ 3, undefined, undefined, 5 ] // convert array-like object to array console.log(Array.from({ 0: "a", 1: "b", length: 2 })); // [ "a", "b" ] // empty items 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(x_iterable, f)-
Apply f to each.
The function f is passed 2 args:
- current element
- current index
// Convert string to array of chars console.log(Array.from("🦋⭐🌞", (a, b) => [a, b])); // [ [ "🦋", 0 ], [ "⭐", 1 ], [ "🌞", 2 ] ] Array.from(x_iterable, f, this-binding)-
- Use this-binding as this (binding) in f.
- If this-binding is not given, undefined is used.