JavaScript Array from() Method

JavaScript Array from() method is used to create a new array instance from an array-like or iterable object(Map or Set). This method is particularly useful when working with various data structures and array-like objects.

Syntax

Array.from(arrayLike[, mapFn[, thisArg]])

Parameters

  1. arrayLike(required): It is an array-like or iterable object to convert to an array.
  2. mapFn(Optional): Map function to call on every array element.
  3. thisArg(Optional): Value to use as this when executing mapFn.

Return Value

Returns a new Array instance.

Visual RepresentationVisual Representation of JavaScript Array from() Method

Example 1: How to Use Array from() Method

let str = 'Italy';
let strArr = Array.from(str);

console.log(strArr);

Output

[ 'I', 't', 'a', 'l', 'y' ]

Example 2: Create an array from a setVisual Representation of Array from a set

let countries = new Set(['Italy', 'USA', 'UK']); 

console.log(Array.from(countries));

Output

[ 'Italy', 'USA', 'UK' ]

Example 3: Array from an array-like object

function arrFrm(){
  return Array.from(arguments);
}
let arr = arrFrm(7, 14, 28);

console.log(arr);

Output

[ 7, 14, 28 ]

In the above example, arguments object inside the function is an array-like object that represents the arguments passed to the function. Then it converts this array-like object into a real array.

Example 4: Using with a mapping function

let data = [7, 8, 9];
let final = Array.from(data, x => x * x);
console.log(final);

Output

[ 49, 64, 81 ]

Browser compatibility

  1. Google Chrome 45
  2. Microsoft Edge 12
  3. Mozilla Firefox 32
  4. Safari 9
  5. Opera 32

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.