Skip to main content

JavaScript Array from Method (Live Playground)

The JavaScript Array from method is used to create a new array instance from an array-like or iterable object.

Here is an example of how you can use the from method:

let arrayLike = { length: 3, 0: 'apple', 1: 'banana', 2: 'cherry' };
let newArray = Array.from(arrayLike);


// Expected output:
// ['apple', 'banana', 'cherry']

In the example above, Array.from(arrayLike) creates a new array using the properties of the arrayLike object.

Live Playground, Try it Yourself

The from method can also accept a map function as a second argument. This map function is applied to each element of the array:

let numbers = [1, 2, 3];
let squares = Array.from(numbers, x => x * x);


// Expected output:
// [1, 4, 9]

In the second example, Array.from(numbers, x => x * x) creates a new array where each number is the square of the corresponding number in the original array.

Live Playground, Try it Yourself

Understanding from can enhance your ability to manipulate and transform data in JavaScript.