JavaScript : How to creates a new array instance from an array-like or iterable object ?

Java Script @ Freshers.in

JavaScript arrays are versatile data structures crucial for managing collections of data. The from() method is a powerful array method that allows for the creation of new arrays from array-like or iterable objects. In this article, we’ll delve into the functionality of from(), explore its syntax, and showcase its practical applications with illustrative examples.

Understanding from()

The from() method in JavaScript creates a new array instance from an array-like or iterable object. It provides flexibility and ease of use when transforming different types of data structures into arrays.

Syntax

The syntax for from() is straightforward:

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

Here, arrayLike represents the array-like or iterable object to convert to an array. mapFunction (optional) is a mapping function to call on each element of the array, and thisArg (optional) is the value to use as this when executing mapFunction.

Examples

Let’s explore various scenarios to understand the versatility of from():

Example 1: Converting a String to an Array

const str = 'hello';
const charArray = Array.from(str);
console.log(charArray);
// Output: ['h', 'e', 'l', 'l', 'o']

Example 2: Mapping Function with from()

const nums = [1, 2, 3, 4];
const squaredArray = Array.from(nums, x => x * x);
console.log(squaredArray);
// Output: [1, 4, 9, 16]

Example 3: Using thisArg Parameter

const set = new Set([1, 2, 3]);
function mapCallback(x) {
  return x * this.multiplier;
}
const mappedArray = Array.from(set, mapCallback, { multiplier: 2 });
console.log(mappedArray);
// Output: [2, 4, 6]
The from() method in JavaScript offers a convenient way to create new arrays from array-like or iterable objects.
Author: user