JS: Array.from

By Xah Lee. Date: . Last updated: .

New in JS2015.

Array.from(xlist)
Convert xlist to array.

xlist is a Array-Like Object or Iterable Object object.

// Convert Array-Like Object to Array
const xx = { 0: "a", 1: "b", length: 2 };
const yy = Array.from(xx);
console.log(Array.isArray(yy));
console.log(JSON.stringify(yy) === '["a","b"]');
// Convert string to array of chars

const tt = "😃😄😅";
const rr = Array.from(tt);

console.log(
  JSON.stringify(rr) === '["😃","😄","😅"]',
);
Array.from(xlist, f)
Apply f to each.

The function f is passed 2 args:

  1. current element
  2. current index
const tt = "😃😄😅";
const yy = Array.from(tt, (a, b) => [a, b]);
console.log(
  JSON.stringify(yy) === '[["😃",0],["😄",1],["😅",2]]',
);
Array.from(xlist, f, thisBinding)
Use thisBinding as this Binding in f. If thisBinding is not given, undefined is used.

Before JS2015

See: Array-Like Object to Array

JavaScript, Array-Like Object

JavaScript, List Object Properties (to Array)