JS: Array.from
(new in ECMAScript 2015)
Array.from(iterable_or)-
Convert iterable_or 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.
🛑 warning: Array.from does not work on general objects. when used on object, it returns a empty array.
/* 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 does not work on general objects. // when used on object, it returns a empty array. const x = Array.from({ a: 1, b: 1 }); console.log(x); // [] console.log(Reflect.ownKeys(x)); // [ "length" ] Array.from(iterable_or, 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(iterable_or, f, this-binding)-
- Use this-binding as this-binding in f.
- If this-binding is not given, undefined is used.