JavaScript Array Array.from() method


The Array.from() method in JavaScript is a static method that creates a new array instance from an array-like or iterable object. This method is particularly useful for converting objects such as NodeList, arguments, or even other iterable collections (like sets or maps) into an array.

Syntax:

Array.from(arrayLike[, mapFunction[, thisArg]]);

Parameters:

  1. arrayLike: An array-like or iterable object to convert into an array. This can be:

    • An array, a string, or an object with a length property (like NodeList).
    • Any iterable object (like Set or Map).
  2. mapFunction (optional): A mapping function that is called for each element in the array-like object. It takes three arguments:

    • currentValue: The current element being processed.
    • index (optional): The index of the current element.
    • array (optional): The array being constructed.
  3. thisArg (optional): A value to use as this when executing the map function.

Return Value:

  • A new array instance.

Key Points:

  • Array.from() creates a shallow copy of the elements from the provided array-like or iterable object.
  • If a mapping function is provided, it is executed on each element of the array-like object before being added to the new array.
  • If the thisArg is provided, it will be used as this when executing the mapping function.

Example 1: Basic usage

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

Example 2: Converting a NodeList to an Array

// Assuming there are some <div> elements in the document let nodeList = document.querySelectorAll('div'); let divArray = Array.from(nodeList); console.log(divArray); // Array of <div> elements

Example 3: Using a Mapping Function

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

Example 4: Converting a Set to an Array

let set = new Set([1, 2, 3, 4]); let arrFromSet = Array.from(set); console.log(arrFromSet); // [1, 2, 3, 4]

Example 5: Using thisArg with a Mapping Function

let obj = { multiplier: 2, multiply(x) { return x * this.multiplier; } }; let arr = Array.from([1, 2, 3], function(x) { return this.multiply(x); }, obj); console.log(arr); // [2, 4, 6]

Summary:

  • The Array.from() method is a versatile tool for converting array-like or iterable objects into arrays in JavaScript.
  • It allows for optional mapping, enabling transformation during the conversion process.
  • This method is useful in various contexts, especially when dealing with DOM elements, strings, and collections, simplifying the process of working with such data structures.