Array.From Using Javascript

Hello Fellow Developers in this blog we are going to talk about a powerful array property from.

The JavaScript Array.from() method is a powerful tool for creating new arrays from existing data. It can be used to convert an array-like or iterable object into a new array, and is particularly useful when working with data from APIs or other sources that may not be in the format of a traditional array.

The Array.from() method takes two arguments: the first is the object to be converted, and the second is an optional map function that can be used to transform the elements of the object as they are added to the new array. Here is an example of using the Array.from() method to convert a NodeList into an array:

var divs = document.querySelectorAll("div");
var divsArray = Array.from(divs);
console.log(divsArray); // [<div>, <div>, <div>, ...]

In this example, the Array.from() method is used to convert the NodeList returned by querySelectorAll() into a new array “divsArray”.

The Array.from() method can also be used to transform the elements of the object as they are added to the new array. In this example, we’ll use the Array.from() method to create a new array with the square of each element in an array-like object:

var numbers = { 0: 1, 1: 2, 2: 3, 3: 4, 4: 5, length: 5 };
var squares = Array.from(numbers, x => x * x);
console.log(squares); // [1, 4, 9, 16, 25]

In this example, the Array.from() method is called on the “numbers” object and the map function takes each element and multiplies it by itself. The returned values are then used to create the new “squares” array.

It’s also possible to use Array.from() to create an array with a specific length and fill it with a given value. For example, you can create an array of a specific length and fill it with zeroes:

var zeroes = Array.from({length: 5}, () => 0);
console.log(zeroes); // [0, 0, 0, 0, 0]

In this example, the Array.from() method is called with an object with a length of 5 and a callback that returns 0. This creates an array of 5 elements, each with the value of 0.

In conclusion, the Array.from() method is a powerful tool for creating new arrays from existing data in JavaScript. It allows you to convert array-like or iterable objects into a new array, and to transform the elements of the object as they are added to the new array. It’s a great choice when you need to work with data from APIs or other sources that may not be in the format of a traditional array. Additionally, it provides a way to create an array with specific length and fill it with a given value.

Submit a Comment

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

Subscribe

Select Categories