JavaScript Array from() Method

In this tutorial, we will learn about the Array from() method in JavaScript. Array from() method is one of the most widely used methods in JavaScript. Lets give a look at the Array from() method in JavaScript first then we will deep dive into the Array from() method with examples.

What is Array from() in JavaScript?

A new instance of an array can be made from an existing array using the Javascript Array from() method. When it comes to integer values, a new array instance simply takes the elements of the existing array, however, when it comes to strings, every letter of the string is turned into an element of the new array instance.

Syntax:

Array.from(object, mapFunction, thisValue)

Parameters: As previously indicated and further defined below, this procedure accepts three parameters:

  • object: The object that will be converted into an array is stored in this parameter.
  • mapFunction: This optional parameter is used to call on each element of the array.
  • thisValue: This parameter, which is optional, contains the context that must be given in order to use it when using the mapFunction. Every time the callback function is called, the context will be used in this way if it is supplied, otherwise, undefined is used by default.

Return value: The elements of the new Array instance that is returned match those of the original array. Every letter of a string is turned into an element of the new array instance in the case of a string.

In ES5, you iterate over all array items and add each one to an intermediate array in order to generate an array from an object that behaves like an array:

function arrayFromArgs() {
    var results = [];
    for (var i = 0; i < arguments.length; i++) {
        results.push(arguments[i]);
    }
    return results;
}
var fruits = arrayFromArgs('Apple', 'Orange', 'Banana');
console.log(fruits);

Output:

[ 'Apple', 'Orange', 'Banana' ]

You may use the Array.prototype's slice() method to condense it as follows:

function arrayFromArgs() {
    return Array.prototype.slice.call(arguments);
}
var fruits = arrayFromArgs('Apple', 'Orange', 'Banana');
console.log(fruits);

The Array from() method, which is new in ES6, creates a new instance of the Array from an object that acts like an array or is iterable. The syntax for the Array from() method is shown below:

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

In this syntax:

  • target is an object to be converted into an array that is iterable or array-like.
  • The map function, or mapFn, should be used on each element of the array.
  • The value used to call the mapFn method is thisArg.

A new instance of Array is returned by the Array from() method, and it contains every element of the source object.

JavaScript Array from() method Examples

Let’s take some examples of using the Array from() method.

A) Create an Array from an Array-like Object

The following example demonstrates how to build a new array from a function's arguments object using the Array from() method:

function arrayFromArgs() {
    return Array.from(arguments);
}

console.log(arrayFromArgs(1, 'A'));

Output:

[ 1, 'A' ]

In this example, we create an array from arguments of the arrayFromArgs() function and return the array.

B) JavaScript Array from() with a Mapping Function

You can run the mapping function on each element of the array that is being formed by using the callback function that is accepted by the Array from() method. See the example below:

function addOne() {
    return Array.from(arguments, x => x + 1);
}
console.log(addOne(1, 2, 3));

Output:

[ 2, 3, 4 ]

The addOne() function's arguments were each increased by one in this example, and the outcome was then added to the new array.

C) JavaScript Array from() with a This Value

You can optionally pass the third argument to the Array from() method if the mapping function is an object. In the mapping function, the object will serve as this value's representation. Think of this illustration:

let doubler = {
    factor: 2,
    double(x) {
        return x * this.factor;
    }
}
let scores = [5, 6, 7];
let newScores = Array.from(scores, doubler.double, doubler);
console.log(newScores);

Output:

[ 10, 12, 14 ]

D) Create an Array from an Iterable Object

You can use the Array from() function to generate an array from any object that has a [symbol.iterator] attribute because it also operates on iterable objects. For instance:

let even = {
    *[Symbol.iterator]() {
        for (let i = 0; i < 10; i += 2) {
            yield i;
        }
    }
};
let evenNumbers = Array.from(even);
console.log(evenNumbers);

Output:

[0, 2, 4, 6, 8]

In this instance:

  • The [System.iterator] that yields even values from 0 to 10 is used to define the even object.
  • Then, from the even object, construct a new array of even numbers using the Array from() method.

Conclusion
In this tutorial, We have learned how to use the JavaScript Array Array from() method to create an array from an array-like or iterable object. We hope this blog will help you in using the Array from() method in JavaScript.

Leave a Reply

Your email address will not be published. Required fields are marked *