Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

JavaScript Array from() Method

Last Updated on April 28, 2023 by Prepbytes

The array.from() method in JavaScript allows us to create a new array from an array-like object or an iterable object. The Array.from() method provides a convenient way to convert other data types, such as strings or sets, into arrays. We will explore the syntax of the Array.from() method, how to use it with different types of input, and some common use cases. By the end of this article, you will have a better understanding of the Array.from() method and how to use it in your JavaScript programs.

What is Array.from() Method in JavaScript?

The Array from() method in JavaScript allows for the creation of a new array instance from an existing array. When it comes to integer values, a new array instance simply takes the elements of the existing array. However, when the existing array contains strings, each letter in the string becomes an element in the new array instance.

Syntax of Array.from() Method

Array.from(object, mapFunction, thisValue)

Parameters of Array.from() Method

As previously indicated and further defined below, the Array.from() Method accepts the following 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 is an optional parameter that 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 this way if it is supplied, otherwise, undefined is used by default.

Return value of Array.from() Method

The Array.from() Method returns the elements of the new Array instance that 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);

ES6 Syntax of Array.from() Method

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.

Examples of Array.from() Method in JavaScript

Let’s look into some of the examples for a better understanding of the Array.from Method.

Creating an Array from an Array-like Object using Array.from()

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

Code:

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.

Using the Array.from() function 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 code given below.

Code:

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.

Using Array.from() in JavaScript with a This Value

We can also pass the third(optional) 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.

Code:

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 ]

Using Array.from() Method to 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. Here is the code for this.

Code:

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 the above code:

  • 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 article, we learned about the Array.from() method in JavaScript that is used to create an array from an array-like or iterable object. We have discussed the syntax and various examples that show the usage of the Array.from() method. We hope this blog will help you in using the Array.from() method in JavaScript.

Frequently Asked Questions(FAQs)

Here are some frequently asked questions related to the array.from() method in JavaScript.

Ques 1. How can you use the Array.from() method to create a new array from a set?
Ans. You can use the Array.from() method to create a new array from a set by passing the set as the first argument, like this: Array.from(mySet).

Ques 2. What happens if the input argument of the Array.from() method is not an array-like or iterable object?
Ans. If the input argument is not an array-like or iterable object, the Array.from() method throws a TypeError.

Ques 3. What is an iterable object in JavaScript?
Ans. An iterable object is an object that can be iterated over with the help of for..of.

Leave a Reply

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