JavaScript Array.from() method


The Array.from() method in JavaScript creates a new array from an array-like or iterable object (such as strings, sets, maps, or arguments objects). It also allows for an optional mapping function to modify elements during the creation of the new array.

Syntax:

Array.from(arrayLike[, mapFn[, thisArg]])
  • arrayLike: The array-like or iterable object to convert to an array.
  • mapFn (optional): A map function to apply to each element before adding it to the new array.
  • thisArg (optional): The value to use as this when executing the map function.

Description:

  • Array.from() can turn any array-like object (e.g., arguments, NodeList) or iterable (e.g., strings, sets) into a real array.
  • You can optionally provide a mapping function, similar to Array.prototype.map(), to apply to each element before returning the final array.
  • If the object is not iterable or array-like, Array.from() will throw an error.

Examples:

1. Convert a string to an array:

const str = 'hello'; const arr = Array.from(str); console.log(arr); // ['h', 'e', 'l', 'l', 'o']

2. Convert a set to an array:

const set = new Set([1, 2, 3]); const arr = Array.from(set); console.log(arr); // [1, 2, 3]

3. Convert an arguments object to an array:

function example() { const arr = Array.from(arguments); console.log(arr); // [1, 2, 3] } example(1, 2, 3);

4. Using a mapping function:

const arr = Array.from([1, 2, 3], x => x * 2); console.log(arr); // [2, 4, 6]

5. Convert an iterable (e.g., a map) to an array:

const map = new Map([['a', 1], ['b', 2]]); const arr = Array.from(map); console.log(arr); // [['a', 1], ['b', 2]]

6. Convert a NodeList to an array:

If you have a list of DOM elements (e.g., from document.querySelectorAll()), you can convert that to an array:

const nodeList = document.querySelectorAll('div'); const arr = Array.from(nodeList); console.log(Array.isArray(arr)); // true

Array-like Objects vs. Iterables:

  • Array-like objects: Objects that have a length property and indexed elements, like arguments or a DOM NodeList.
  • Iterables: Objects that can be iterated over, such as strings, sets, maps, etc.

Summary:

  • Array.from() is useful when you need to create a true array from array-like objects or iterables.
  • It provides a concise and reliable way to convert data structures to arrays and offers an optional mapping function to process elements as they're added to the new array.